在 DataGrid 控件中绑定 DropDownList t 数据表列



我得到了DataGrid控件,它从此数据网格中的DataTable获取其数据,我想将DropDownList控件与其在数据表中的相关数据绑定

DropDownList commentDrop = (DropDownList)packageCommentDataGrid.FindControl("commentDrop");
       commentDrop.DataSource = dt;
        commentDrop.DataTextField = dt.Columns["CommentString"][0];
        commentDrop.DataValueField = dt.Columns["CommentP"][0];

并且 ItemDataBound 事件将如下所示:

protected void packageCommentDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
    if (e.Item.ItemType==ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
    {
        DropDownList commentDrop = (DropDownList)e.Item.FindControl("commentDrop");
    }
}

谢谢

如果我理解正确,这就是你想要做的。

第一:您必须将具有DropDownListGridView列转换为 TemplateField 。确保DropDownList<TemplateField><ItemTemplate><DropDownList id="" runat="server" /></ItemTemplate></TemplateField>内。

第二:在代码隐藏中创建Gridview.RowDataBound事件处理程序。然后在此方法中执行以下操作:

if(e.Row.RowType == DataControlRowType.DataRow)
{
    DropDownList ddl = (DropDownList)e.Row.Cells["Column Name / Index here"].FindControl("commentDrop");
    ddl.DataSource = dt;
    ddl.DataTextField = "Column Name";
    ddl.DataValueField = "Column Name";
    ddl.DataBind();
}

最新更新