Wednesday, October 25, 2006

Handling null values when binding to ASP.NET 2.0 DropDownList Controls

Frequently when using 2 way data binding on data controls such as the FormView or DetailsView, DropDownList boxes are used to allow users to select pre-populated values.

Often in this situation the data item the DropDownList control is being bound to contains a null value. In these situations the ASP.NET compiler will throw an exception (SelectedValue property is set to a value not in its collection of list items).

To solve this issue it is necessary to add in a ListItem with an empty value to the DropDownList. To do this add the following line to your DropDownList making sure you also set the property of the AppendDataBoundItems to "true" so that it will be appended to the list:

<asp:dropdownlist AppendDataBoundItems="true">
<asp:listitem value="" text="Select a value"></asp:listitem>
</asp:dropdownlist>


To make your application more userfriendly it would be nice to programmatically show the null value ListItem when your DropDownList has not been bound to a value. To do this we add an
OnDataBound event to the DropDownList control and check to see if it has a selected value. If it doesn't, then we want to show the null value ListItem. Make sure you set the value of Enabled to false on the ListItem so it doesn't appear.

Add the OnBoundEvent to the control:
<asp:dropdownlist id="MyDropDownList" runat="server" OnDataBound="AddNullValueToDropDownList_DataBound" AppendDataBoundItems="true">
<asp:listitem value="" text="Select a value" Enabled="false"></asp:listitem>
</asp:dropdownlist>

Create the event in the code behind:
protected void AddNullValueToDropDownList_DataBound(object sender, EventArgs e)
{
DropDownList dropdownlist = (DropDownList)sender;
if (dropdownlist.SelectedValue == string.Empty)
{
dropdownlist.Items[0].Enabled = true;
}
}

That's it! Now you can easily databind a DropDownList to your favourite data control with null values.