0

オンラインストアのWebサイトを作成したい。

サイト内の商品を表示するデータリストを作成しました。ユーザーが選択した商品のproductIDを取得してショッピングカートに追加するために、LinkBut​​tonをデータリストに配置しました。

 <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");

このページにはグリッドビューがあり、それをsession["addtocart"]にバインドしたいと思います。ページが読み込まれると、グリッドビューに、セッション["cart"]にあるIDが選択された製品が表示されますが、機能せず、次のエラーが発生しました: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"]に格納されている整数リストオブジェクトの値を整数に変換できないと思います。エラーはセッションオブジェクトから整数リストへの変換に起因しますが、誰かが私を助けてくれたら、この問題を解決する方法がわかりません。私はとても感謝しています。

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

問題は Sql パラメータにあります。List<int>あなたがやろうとしているように、型を Int32 にキャストすることはできません。とにかく List オブジェクトは iConvertible を実装していないように見えるので、別のアプローチが必要になります。

私は通常、あなたが行っているように SqlDataSource を使用しませんが、必要なクエリの適切な構文を構築できる方法を次に示します。

マークアップを次のように更新します。

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

次に Page_Load で、次のように接続文字列を作成します。

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();
}

私が言ったように、マークアップでこれを行う方法があるかもしれませんが、それは私がよく知っているものではありません.

List を継承して iCovertible を実装するクラスを作成することもできますが、SqlParameter として機能する方法が思い浮かびません。さらに、私の記憶が正しければ、iConvertible インターフェイスは 15 個の関数のようなものなので、この 1 つのインスタンスだけでも多くの作業が必要なように思えます。

于 2012-10-07T19:17:57.103 に答える