I have a DropDownList in a template column of a GridView control. The GridView is bound to a list of objects. Each object has a property of type int which corresponds to a value in one of the DropDownLists ListItems. I could set the selected item programatically by adding a DataBind event to the drop down, but I'm wondering if there's a way to set the selected item by using a code block in the aspx markup.
Be cautious in this design. To create grid drop downs in this manner means that for every option in a drop down, you are going to be repeating for every single row. This can very quickly added up to page sizes that are over a MB if you have more than a few rows or multiple drop down columns, which will degrade performance.
That being said, you can do this in the mark up by using the context binding script tags:
<asp:DropDown id="dropDown1" SelectedValue='<%# Eval("Key") %>' runat="server"/>
The context binding tags also let you call public/protected functions on the page/user control as:
<asp:DropDown id="dropDown1" SelectedValue='<%# myFunction((int) Eval("Key")) %>' runat="server"/>
public string myFunction(int key){
return key.ToString();
}
As an alternative to producing the same repetitive HTML for every row, you could make those drop downs autocompleters or create a hidden drop down that only renders the HTML once and then uses JQuery or JavaScript to populate all your grid drop downs clientside.