Thursday, February 7, 2008

OutOfRangeAwareDropDownList - .NET 2.0, C#

Another big problem I've come across (and I know I'm not the only one) has to do with using databinding on DropDownLists.

There is a common issue that crops up. Say the items in the listbox get out of sync with records in the backend datastore. For example the value "foo" is in a data record, but "foo" doesn't exist in the DropDownList. When you pull up the record using databinding (SelectedValue='<%# Bind("FooColumn") %>') you'll get an error like "'lstBadFooList' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value".

I've come up with a solution for this! It's a custom control that I've named, appropriately enough, OutOfRangeAwareDropDownList. What it does is check to see if it's throwing this error, and if it is, it just decides to bind to nothing. Not much to it, but it saves a lot of headaches.

Here's the code:

using System;
using System.Collections;
using System.Web.UI.WebControls;

//this dropdown control overrides the databinding event
//it is used to overcome an issue where an element originally put into the record
//no longer exists in the dropdown list

namespace kevnls.controls
{
public class OutOfRangeAwareDropDownList : DropDownList
{
protected override void PerformDataBinding(IEnumerable dataSource)
{
try
{
base.PerformDataBinding(dataSource);
}
catch (ArgumentOutOfRangeException)
{
base.SelectedIndex = -1;
}
}
}
}

All you have to do is compile this into a .dll and then use it in your project. The absolute easiest way to use it in Visual Studio 2005 is to right-click in your toolbox and select "Choose Items..." and find the .dll, and a new control will show up in your toolbox. Then you can just drag it into your .aspx page like any other control and Visual Studio will take care of registering the assembly and importing the reference. Simple as that.

No comments: