There are a number of options for databinding nested controls in the GridView templates.
The easiest, and the one I use when I can, is to use an ObjectDataSource and bind your dropdownlist to that.
If this isn't an option, then you can bind in the RowDataBound event. The example on MSDN is lacking, but if you follow that example (C#), and where it says:
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
You would have something like:
DropDownList ddlWhatever = e.Row.FindControl("ddlWhatever") as DropDownList;
if(ddlWhatever != null) { /* bind data to it and call ddlWhatever.DataBind(); */ }
Since the EditItemTemplate and the InsertItemTemplate aren't rendered at the same time, I usually keep the control names the same in each template to simplify the databound event in the code behind. But, there's nothing stopping you from having a ddlEditItems
and a ddlInsertItems
and binding those differently in the databound event.
Another trick I've used before is binding to the DropDownList with the OnInit event of the dropdown. For instance:
// web form
<asp:DropDownList id="ddlWhatever" AutoPostBack="True"
runat="server" OnInit="ddlWhatever_Init">
// Code behind
protected void ddlWhatever_Init(object s, EventArgs a)
{
object[] years = {
new { Year = 2009 }, new { Year = 2010 }
};
ddlWhatever.DataSource = years;
ddlWhatever.DataTextField = "Year";
ddlWhatever.DataValueField = "Year";
ddlWhatever.DataBind();
}
I've had some people tell me not to do it this last way (i.e. a control shouldn't be responsible for binding itself). I disagree, and don't recall seeing anything related to that claim in Microsoft's Framework Design Guidelines. When it all comes down to it, I like the last way when I can't use an ObjectDataSource, but I do have to also code to the acceptance level of fellow developers. :D
The rules I usually stick with:
- Use ObjectDataSource when it's quick and easy
- Use GridView RowDataBound when the nested control's items are dependent on other values in the GridView
- Use the OnInit method if you're just binding data, keeping in mind that you can't access other controls when this method is fired (e.g. GridView may not have been initialized yet)
I hope that helps, I went through similar frustration with the MSDN's lack of GridView examples.