0

我想创建一个在线商店网站。

我创建了一个数据列表,在我的网站中显示我的产品,我将 LinkBut​​ton 放在我的数据列表中,以获取用户选择的产品的 productID 并将其添加到购物车。

 <asp:LinkButton ID="LinkButton1" runat="server" Text="Add To Cart" CommandName="addtocart" CommandArgument='<%# Eval("id")%>' >

当用户单击链接按钮时,会触发此事件:

protected void theDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
//this add the selected product-id to the list<int> and put it in the 
//  session["addtocart"]
        if (e.CommandName == "addtocart")
        {                                 
            int productid = Convert.ToInt32(e.CommandArgument);
            Label6.Text = productid.ToString();


            List<int> productsincart = (List<int>)Session["addtocart"];
            if (productsincart == null)
            {
                productsincart = new List<int>();
            }

            productsincart.Add(productid);

            Session["addtocart"] = productsincart;
} 

之后当用户点击文本为“显示购物车”的按钮时,用户将看到shoppingcart.aspx页面

    Response.Redirect("shoppingcart.aspx");

在此页面中,我有一个 gridview,我想将其绑定到 session["addtocart"]; 当页面加载 gridview 时,会显示其 id 在 session["cart"] 中的所选产品,但它不起作用并且发生此错误:System.InvalidCastException:对象必须实现 IConvertible。

这是相关代码:

            <asp:GridView ID="GridView3" runat="server"  
            DataSourceID="SqlDataSource1"   >

           <columns>
            <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
            <asp:BoundField DataField="name" HeaderText="post" SortExpression="post" />
            <asp:BoundField DataField="price" HeaderText="salary" 
                SortExpression="salary" />
            <asp:BoundField DataField="color" HeaderText="years" SortExpression="years" />

        </columns>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:employeeConnectionString4 %>" 
        SelectCommand="SELECT * FROM [products] WHERE ([productid] = @productid)">
        <SelectParameters>
            <asp:SessionParameter DefaultValue="7" Name="cart" SessionField="cart" 
                Type="Int32" />
        </SelectParameters>

我知道问题与 GridView3 和 Session["addtocart"] 有关,我认为 GridView3 无法将存储在 Session["addtocart"] 中的整数列表对象的值转换为整数,似乎我的错误来自从会话对象到整数列表的转换,但如果有人帮助我,我不知道如何解决这个问题,我变得非常感激。

The Session["cart"] 中的对象是一个整数列表,其中包含用户选择购买的产品 ID 列表。它给了我这个错误:

对象必须实现 IConvertible。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidCastException:对象必须实现 IConvertible。

源错误:

在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。

堆栈跟踪:

[InvalidCastException: Object must implement IConvertible.]
System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider)   +2880621
System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges) +141
System.Web.UI.WebControls.Parameter.GetValue(Object value, Boolean ignoreNullableTypeChanges) +63
System.Web.UI.WebControls.ParameterCollection.GetValues(HttpContext context, Control control) +301
System.Web.UI.WebControls.SqlDataSourceView.InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList) +264
System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +472
System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +19
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +142
System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +73
System.Web.UI.WebControls.GridView.DataBind() +4
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +82
System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +72
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +44
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
4

1 回答 1

0

The problem is in your Sql Parameter. It can't cast type List<int> into Int32 as you're trying to do. And it looks like the List object does not implement iConvertible anyway, so you'll need a different approach.

I don't normally use SqlDataSource as you are doing, but here is a way you can build the proper syntax for the query you want:

Update your markup to this:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:employeeConnectionString4 %>" />

Then on Page_Load, build your connection string like this:

public void Page_Load(object sender, EventArgs e)
{
    this.SqlDataSource1.SelectCommand = String.Format("SELECT * FROM [products] WHERE [productid] in ({0}))", GetInValues(Session["cart"] as List<int>));
}
public string GetInValues(List<int> lst)
{
    System.Text.StringBuilder sValues = new System.Text.StringBuilder();
    if (i == null)
        sValues.Append(0);
    else
    {
        foreach (int i in lst)
        {
            if (sValues.Length > 0)
                sValues.Append(", ");
            sValues.Append(i);
        }
    }
    return sValues.ToString();
}

Like I said, there may be a way to do this in the Markup, but it's not something I'm familiar with.

You could also create a class that inherits List and implement iCovertible, but I can't think of a way that's going to work as a SqlParameter. Plus the iConvertible interface is like 15 functions if I remember correctly, so it seems like a lot of work for just this one instance.

于 2012-10-07T19:17:57.103 回答