首页 > 解决方案 > 如何从数据库中获取数据列表中的特定 ID?

问题描述

我正在尝试id从数据库中获取特定信息,但由于某些原因,我在id.

在页面加载中:

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

标签: c#htmlasp.net

解决方案


好的,所以我的建议是:将以下链接按钮添加到您的项目模板

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

推荐阅读