【问题标题】:Populating Gridview's Drop Down List depending on database value根据数据库值填充 Gridview 的下拉列表
【发布时间】:2021-05-19 05:42:32
【问题描述】:

我想在我的代码中获得一些帮助,我想要做的是填充我的下拉列表,该列表显示可用数量(存储在数据库中)但是当我尝试在行中找到控件时得到一个空引用异常,它说行为空。

这是包含我的下拉列表的模板字段

<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>

还有我的代码

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

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    请试试这个

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

    【讨论】:

    • 它仍在向我的下拉列表抛出 System.NullReferenceException,我创建了一个 for 循环,以便使用从 1 到 OnHandQTY 的数字填充下拉列表
    猜你喜欢
    • 1970-01-01
    • 2013-06-20
    • 2012-02-09
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2014-08-27
    相关资源
    最近更新 更多