如何从数据库中获取数据到gridview中的下拉列表

时间:2017-05-12 07:31:41

标签: c# gridview

下面给出的代码不起作用所以请给出建议我在" foreach循环" ="对象未设置为对象的实例"所以请帮助它或对相关代码进行任何更改。

 //////////// html design /////////////////
<asp:GridView ID="DataExtensionList" Style="width: 150%;" runat="server" AutoGenerateColumns="False" OnRowDataBound="DataExtensionList_RowDataBound">
    <Columns>
      <asp:TemplateField HeaderText="Rate Plan" ItemStyle-Width="15%">
         <ItemTemplate>
             <asp:DropDownList ID="ddrateplan" runat="server" CssClass="form-control" AutoPostBack="true"OnSelectedIndexChanged="ddrateplan_SelectedIndexChanged" Style="margin: 0 !important; padding: 0 !important;" SelectedValue='<%# Eval("rate_plan") %>' ValidationGroup="add"> 
             </asp:DropDownList>
         </ItemTemplate>
      </asp:TemplateField>
    </Columns>
</asp:GridView>

////////////c# code///////////////////
protected void DataExtensionList_RowDataBound(object senderGridViewRowEventArgs e)
{
    foreach (GridViewRow row in DataExtensionList.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)row.FindControl("ddrateplan");
            DataTable dt = new DataTable();
            dt = b.annex1_rateplan();
            ddl.DataSource = dt;
            ddl.DataTextField = "rate_plan";
            ddl.DataValueField = "rt_id";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("--Select--", "0"));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

为什么在rowdatabound中使用foreach? rowdatabound事件将为每一行执行一次。我认为你应该把它改成这样的东西:

protected void DataExtensionList_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.DataRow)
        return;
    DropDownList ddl = (DropDownList)e.Row.FindControl("ddrateplan");
    DataTable dt = new DataTable();
    dt = b.annex1_rateplan();
    ddl.DataSource = dt;
    ddl.DataTextField = "rate_plan";
    ddl.DataValueField = "rt_id";
    ddl.DataBind();
    ddl.Items.Insert(0, new ListItem("--Select--", "0"));
}