Thursday, December 18, 2008

DropDownList in a DataGrid set to current data value

This is how you put a dropDownList in a DataGrid and have the DropDownList initialize itself on the current value of the bound data field. This code additionally takes care of the case where the bound field has not been set yet in the data.

In the GridView, the BoundField is changed to a TemplateField and populated like this:

<asp:TemplateField HeaderText="Priority" SortExpression="some_select_field">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("some_select_field") %>'>
<asp:ListItem Value="H">H</asp:ListItem>
<asp:ListItem Value="M">M</asp:ListItem>
<asp:ListItem Value="L">L</asp:ListItem>
<asp:ListItem Value="">Not Set</asp:ListItem>

</asp:DropDownList>

</EditItemTemplate>

<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("some_select_field") %>'></asp:Label>

</ItemTemplate>

</asp:TemplateField>



'some_select_field' is just some field returned by the SQLDataSource's SelectCommand:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:FAA_ConnectionString %>"
ProviderName="<%$ ConnectionStrings:FAA_ConnectionString.ProviderName %>" SelectCommand="Select some_select_field from some_sql_table">

</asp:SqlDataSource>


Dave