简体   繁体   English

根据数据库值填充 Gridview 的下拉列表

[英]Populating Gridview's Drop Down List depending on database value

I would like to get some help here in my code, what am I trying to do is to populate my drop down list which shows the available quantity (stored in database) but when I try to find the control in the row I get a null reference exception it says row was null.我想在我的代码中获得一些帮助,我想做的是填充我的下拉列表,该列表显示可用数量(存储在数据库中)但是当我尝试在行中找到控件时,我得到一个 null参考异常它说行是 null。

Here is the template field that has my drop down list这是包含我的下拉列表的模板字段

<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
   <EditItemTemplate>
        <asp:DropDownList ID="ddlQuantity" runat="server">
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="Label4" runat="server" Text='<%# Bind("Quantity") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

and my code behind和我背后的代码

protected void Cart_GV_RowEditing(object sender, GridViewEditEventArgs e) {
        Cart_GV.EditIndex = e.NewEditIndex;
        GridViewRow row = (sender as Control).Parent.Parent as GridViewRow;
        DropDownList ddlQuantity = row.FindControl("ddlQuantity") as DropDownList;
        string cartitemid = Cart_GV.DataKeys[e.NewEditIndex].Value.ToString();
        conn.Open();
        SqlCommand checkQuantity = new SqlCommand("SELECT OnHandQTY FROM Inventory INNER JOIN Cart_Item ON Inventory.ProductID = Cart_Item.ProductID WHERE CartItemID = '" + cartitemid + "';", conn);
        int availalbleQuantity = (int)checkQuantity.ExecuteScalar();
        conn.Close();
        for (int i = 1; i <= availalbleQuantity; i++) {
            ListItem item = new ListItem(i.ToString(), i.ToString());
            ddlQuantity.Items.Add(item);
        }
        ViewUserCart();
    }

Please Try this one请试试这个

protected void Cart_GV_RowEditing(object sender, GridViewEditEventArgs e) {
    Cart_GV.EditIndex = e.NewEditIndex;
    GridViewRow row = (sender as Control).Parent.Parent as GridViewRow;
    DropDownList ddlQuantity = row.FindControl("ddlQuantity") as DropDownList;
    string cartitemid = Cart_GV.DataKeys[e.NewEditIndex].Value.ToString();
    conn.Open();
    SqlCommand cmd = new SqlCommand("SELECT OnHandQTY FROM Inventory INNER JOIN Cart_Item ON Inventory.ProductID = Cart_Item.ProductID WHERE CartItemID = '" + cartitemid + "';", conn); 
    SqlDataAdapter sda = new SqlDataAdapter(cmd);  
    DataTable dt = new DataTable();  
    sda.Fill(dt);  
    con.Close();  
    ddlQuantity.DataSource = dt;  
         
    ddlQuantity.DataTextField = "OnHandQTY";  
    ddlQuantity.DataValueField = "OnHandQTY";  
    ddlQuantity.DataBind();
    ViewUserCart();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM