Asp – how to bind data to dropdown control in gridview

asp.net

i have an gridview which i am binding to datatable called dtimages
inside the gridview i have a dropdown control which is under edit item template

so once the user clciks the edit button then the dropdown control should get binded with a table called dtResource
and all other textbox fields which is under different edititemtemplate
will get bind with the datatable dtimages

so how to bind these dropdown control with different table
thank you

Best Answer

Implement the OnDataBinding event for the dropdownlist.

// In your aspx page
<asp:DropDownList ID="yourDDL" runat="server" DataTextField="yourTextFieldName" DataValueField="yourValueFieldName" OnDataBinding="yourDDL_DataBinding">
</asp:DropDownList>

// In your codebehind .cs file
protected void yourDDL_DataBinding(object sender, System.EventArgs e)
{
    DropDownList ddl = (DropDownList)(sender);
    // This could be a List of objects, DataTable, DataSet, whatever
    ddl.DataSource = GetCachedData();  
    ddl.DataBind();
}

The GetCachedData() is something you should have so that you are not building or hitting the database each time to get the result that your ddl is being bound to. This is not required though, you could hit the database each time but it cache it reduces the workload each time you switch to edit mode.