如何从数据库获取数据列表中的特定ID?

时间:2019-03-07 10:00:51

标签: c# html asp.net

我正在尝试从数据库中获取特定的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));
}

1 个答案:

答案 0 :(得分:0)

好的,所以我的建议是:在商品模板中添加以下链接按钮

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