簡體   English   中英

如何從數據庫中獲取數據列表中的特定 ID?

[英]How do I get specific ID in data list from database?

我試圖從數據庫中獲取特定的id但由於某些原因我在id得到 null 。

在頁面加載中:

string id = Request.QueryString["ProductID"];

protected void Button1_Click(object sender, EventArgs e)
{
    if (Session["myCart"] == null)
    {
        myCart = new Cart();
        Session["myCart"] = myCart; 
    }

    string id = Request.QueryString["ProductID"];
    int id2 = this.DataList1.SelectedIndex;
    myCart = (Cart)Session["myCart"];

    DataTable dt = ds.SelectQuery("SELECT * FROM Products where ProductID = '" + id + "'");
    DataRow row = dt.Rows[0];

    myCart.Insert(new CartItem(int.Parse(id), row["ProductName"].ToString(), int.Parse(row["UnitPrice"].ToString()), 1));
}

好的,所以我的建議是:將下面的鏈接按鈕添加到您的項目模板

<asp:LinkButton ID="LinkButton1" runat="server" CommandName="select">Select</asp:LinkButton>

然后處理代碼文件中的SelectedIndexChange事件:

protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = DataList1.SelectedIndex;
    //Your product id should be bound to a label in the item template
    Label lbl = (Label)DataList1.Items[index].FindControl("IDoftheControlcontainingid");
    string id=lbl.Text;

    //use the id variable to get the product and add to cart. your old code
    if (Session["myCart"] == null)
    {
        myCart = new Cart();
        Session["myCart"] = myCart; 
    }

    myCart = (Cart)Session["myCart"];

    DataTable dt = ds.SelectQuery("SELECT * FROM Products where ProductID = '" + id + "'");
    DataRow row = dt.Rows[0];

    myCart.Insert(new CartItem(int.Parse(id), row["ProductName"].ToString(), int.Parse(row["UnitPrice"].ToString()), 1));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM