如何在c#中绑定gridview rowdatabound中的dropdownlist?

时间:2018-03-05 10:18:18

标签: c# gridview data-binding

这是我在 GridView

中的编辑项目模板中的下拉列表
<asp:DropDownList runat="server" ID="ddlFl" AutoPostBack="true"
 OnSelectedIndexChanged="ddlFl_SelectedIndexChanged"
      DataValueField='<%# Eval("ID").ToString() %>'>
   <asp:ListItem Text="[ Select ]" Value=""></asp:ListItem>
   <asp:ListItem Text="-------------" Value=""></asp:ListItem>
   <asp:ListItem Text="0" Value="0"></asp:ListItem>
   <asp:ListItem Text="1" Value="1"></asp:ListItem>
   <asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:DropDownList>

当用户点击编辑时,网格进入编辑模式。

如果是产品子类别,我们会将tbl_2表中可用的所有产品类别列表加载到下拉列表中,并可供用户选择,如果在行中存在值,则会在下拉列表。

我尝试过这种模式没有成功,因为我有错误:

  

只能使用Eval(),XPath()和Bind()等数据绑定方法   在数据绑定控件的上下文中使用。

如何解决这个问题?

你能帮助我吗?

提前感谢您的帮助,非常感谢。

protected void ddlFl_SelectedIndexChanged(object sender, EventArgs e)
{

    DropDownList btn = (DropDownList)sender;
    string indexID = btn.DataValueField;
    string LinkID = btn.SelectedValue;
    GridViewRow row = (GridViewRow)btn.NamingContainer;

    Response.Write(LinkID);

}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {

        if (e.Row.DataItem != null)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList ddlFl = (DropDownList)e.Row.FindControl("ddlFl");
                ddlFl.DataTextField = "Dip";
                ddlFl.DataValueField = "Dip";
                ddlFl.DataSource = RetrieveSubCategories();
                ddlFl.DataBind();
                DataRowView dr = e.Row.DataItem as DataRowView;
                ddlFl.SelectedValue = dr["Dip"].ToString();
            }
        }
    }
}


private DataTable RetrieveSubCategories()
{
    DataTable dtSubCategories = new DataTable();

    sql = @String.Format(" SELECT Dip FROM `tbl_2` GROUP BY Dip; ");

    using (OdbcConnection myConnectionString =
      new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
    {
        using (OdbcCommand cmd = 
            new OdbcCommand(sql, myConnectionString))
        {
            {
                OdbcDataAdapter adapter = 
                    new OdbcDataAdapter(cmd);
                adapter.Fill(dtSubCategories);
            }
        }
    }
    return dtSubCategories;
}

1 个答案:

答案 0 :(得分:1)

DataSource必须位于第一个位置,然后是数据文本和值字段:

DropDownList ddlFl = (DropDownList)e.Row.FindControl("ddlFl");
ddlFl.DataSource = RetrieveSubCategories();
ddlFl.DataTextField = "Dip";
ddlFl.DataValueField = "Dip";
ddlFl.DataBind();