Bind DropDownList t Datatable Column inside DataGrid Control

dotmido picture dotmido · Jun 12, 2012 · Viewed 10.6k times · Source

i got DataGrid Control that get its Data From DataTable inside this DataGrid i want to bound DropDownList Control with its related data in DataTable

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

and the ItemDataBound Event will be like this :

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");

    }
}

Thanks,

Answer

Mr.GT picture Mr.GT · Jun 12, 2012

If I understand you correctly this is what you'll want to do.

First: You will have to convert the GridView column that has the DropDownList to TemplateField. Make sure the DropDownList is inside the <TemplateField><ItemTemplate><DropDownList id="" runat="server" /></ItemTemplate></TemplateField>.

Second: Create the Gridview.RowDataBound event handler in you code behind. Then inside this method do the following:

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