0

在使用 c# 的 asp.net 网站中,当我尝试从数据库表 Product 的下拉列表中获取产品列表时,我收到有关调试“指定转换无效”的消息。谁能指出错误??请它真的很紧急。

这是我的堆栈跟踪:

 [InvalidCastException: Specified cast is not valid.]
   Order.GetSelectedProduct() +371
   Order.Page_Load(Object sender, EventArgs e) +40
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +44
   System.Web.UI.Control.OnLoad(EventArgs e) +83
   System.Web.UI.Control.LoadRecursive() +120
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3955

订单.aspx.cs:

   public partial class Order : System.Web.UI.Page
{

    private Product selectedProduct;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            ddlProducts.DataBind();
        selectedProduct = this.GetSelectedProduct();
        lblName.Text = selectedProduct.Name;
        lblShortDescription.Text = selectedProduct.ShortDescription;
        lblLongDescription.Text = selectedProduct.LongDescription;
        lblUnitPrice.Text = selectedProduct.UnitPrice.ToString("c");
        imgProduct.ImageUrl = "Images/Products/" + selectedProduct.ImageFile;
    }




    private Product GetSelectedProduct()
    {
        DataView productsTable = (DataView)
            SqlDataSource2.Select(DataSourceSelectArguments.Empty);
        productsTable.RowFilter = "P_Id = '" + ddlProducts.SelectedValue + "'";
        DataRowView row = (DataRowView)productsTable[0];
        Product p = new Product();
        p.ProductID = row["P_Id"].ToString();
        p.Name = row["Title"].ToString();
        p.ShortDescription = row["Desc"].ToString();
        p.LongDescription = row["Desc_full"].ToString();
        p.UnitPrice = (decimal)row["Price"];
        p.ImageFile = row["P_image"].ToString();
        return p;
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            CartItem item = new CartItem();
            item.Product = selectedProduct;
            item.Quantity = 1;
            this.AddToCart(item);
            Response.Redirect("Cart.aspx");
        }

    }


    private void AddToCart(CartItem item)
    {
        SortedList cart = this.GetCart();
        string productID = selectedProduct.ProductID;
        if (cart.ContainsKey(productID))
        {
            CartItem existingItem = (CartItem)cart[productID];
            existingItem.Quantity += 1;
        }
        else
            cart.Add(productID, item);
    }


    private SortedList GetCart()
    {
        if (Session["Cart"] == null)
            Session.Add("Cart", new SortedList());
        return (SortedList)Session["Cart"];
    }
}

订单.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Order.aspx.cs" Inherits="Order" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Welcome to LetsDressUp</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

     Please select a product:
       <br />

        <asp:DropDownList ID="ddlProducts" runat="server" 
            DataSourceID="SqlDataSource2" DataTextField="Title" DataValueField="P_Id">
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT [P_Id], [Title], [Desc], [Desc_full], [Price], [P_image] FROM [Product]">
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            SelectCommand="SELECT * FROM [Product]" 
            onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource>
      <br />

      <table>
      <tr>


       <td class="style1">
                    <asp:Label ID="lblName" runat="server" 
                        style="font-weight: 700; font-size: larger">
                    </asp:Label>
                </td>
                <td class="style2" rowspan="4">
                </td>
                <td rowspan="4" valign="top">
                    <asp:Image ID="imgProduct" runat="server" Height="200px" />
                </td>

      </tr>

      <tr>
                <td class="style1">
                    <asp:Label ID="lblShortDescription" runat="server">
                    </asp:Label>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    <asp:Label ID="lblLongDescription" runat="server">
                    </asp:Label>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    <asp:Label ID="lblUnitPrice" runat="server" 
                        style="font-weight: 700; font-size: larger">
                    </asp:Label>
                    <asp:Label ID="Label2" runat="server" Text="each"
                        style="font-weight: 700; font-size: larger">
                    </asp:Label>
                </td>
            </tr>


      </table>

      <asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click" 
            Text="Add to Cart" />
&nbsp;<asp:Button ID="btnCart" runat="server" PostBackUrl="~/Cart.aspx" 
            Text="Go to Cart" />
    </div>
    </form>
</body>
</html>

谢谢你的帮助。

4

1 回答 1

0

您可以使用 aforeach循环遍历数据视图对象的行。

foreach (DataRowView rowView in productsTable)
{
    DataRow row = rowView.Row;
    // Do something with the row //

    // and if you just wanted to process the first record
    //   use break to end the loop
    break;
 }

或者您可以使用FirstOrDefault扩展方法来获取第一行,类似于您在方法中尝试执行的操作

DataRowView rowView = productsTable.FirstOrDefault<DataRowView>()
于 2013-10-12T21:25:32.483 回答