DataBinding DropDown SelectedValue Property

While working on an application I found the need to databind the SelectedValue property of a drop down. However I noticed that intellisense doesn't pick it up. So I asked around and was told that even though it doesn't show up using intellisense it does work. So I tried it and sure enough it worked wonderfully.

Now the value of this may not be apparent but if you are doing custom in line editing in a grid for example it can be very handy you can bind the default value of the drop down to what the value for that field is currently and populate the drop down with a list of all valid values. Additionally you can just call Databind on the grid in that case and it will populate the elements for you if you have it setup correctly.

To see what I'm talking about look at this example.

<asp:GridView runat="server" ID="gvSample" DataSource='<%# GetFavoriteFoodList() %>'>
<asp:BoundField DataField="UserName" />
<asp:DropDownList runat="server" ID="ddlFavoriteFood" DataSource='<%# GetFood() %>'
DataTextField="FoodName" DataValueField="FoodId" SelectedValue='<%# Eval("FoodId") %>'>
<asp:Label runat="server" ID="lblFavoriteFood" Text='<%# Eval("FoodName") %>'>

Now in the above code I'm assuming there are functions called GetFood() and GetFavoriteFoodList(). I'm also assuming that the returned data has the fields used for databinding. The above sample is a little silly but it displays a simple case where databinding the SelectedValue property is useful. I created this sample on the fly and it isn't live code so I apologize for any coding mistakes. Also I'm relatively new to template columns in general.

I don't claim to be an expert of any kind this is just me tinkering with technology. Its what I do.


Popular posts from this blog

VK9 - Milestone8 Completed

VK9 - Milestone13 Completed

VK9 - Milestone16 Completed