DropDownList.SelectedValue only throws exceptions on page postbacks?

by Dominic Zukiewicz 28. February 2008 15:56
Load a, ASP .NET DropDownList with values. Assign the .SelectedValue to an item that doesn't exist, and the DropDownList will happily continue, defaulting to the first entry in the drop-down.

Now, on the postback, try to select this value AGAIN, and you get an exception!? Why ... well, thats just the way the component is coded!! So therefore, the first assignment will work ALWAYS (as long as it is the first page load), and otherwise it will throw an ArgumentOutOfRangeException.

I am as of yet unsure why it was created this way, but the only way round it, is to check it exists for yourself, and cater for it anyway. Below is a quick example which will re-create the error.

public void Page_Load( .... )
{
     if(!Page.IsPostBack)
     {
          ListItem li = new ListItem("key","value");
          dropDownList1.Items.Add(li);
     }
     dropDownList1.SelectedValue = "bogusvalue!";
}


Run that page twice and it will load the first time, and fail the second!

Tags:

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar