views:

330

answers:

3

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.

A: 

Hey,

You can set it in the markup via:

<ItemTemplate>
<asp:DropDown .. SelectedValue='<%# Eval("Key") %>' />
</ItemTemplate>

Depends on how you bind it, are you using a data source control? Whatever the case, I have noticed that this approach it may try to set the value before the items get bound and that may throw an exception. Not sure, had that happen once, thought it may be that, but I should have looked into it more in-depth.

HTH.

Brian
A: 

you can also use RowDataBound event of GridView or you can select in markup as described by @Brian

Adeel
+3  A: 

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.

jjacka