Be careful when reusing ListItems

by Christoph Herold 17. März 2009 12:12

Yesterday, I had one of those WTF moments. I had a page with a form for entering two addresses. Both had the same fields, including a RadioButtonList with identical items. Since the items are resourced, I decided to optimize the performance by reusing the ListItems like so:

ListItem[] items = new ListItem[2];
items[0] = new ListItem(this.GetString("salutation.Mister"), "Mr");
items[1] = new ListItem(this.GetString("salutation.Misses"), "Mrs");
this.salutation.Items.AddRange(items);
this.salutation2.Items.AddRange(items);

Simple eh. Everything seems to be ok. And was I amazed, when I tested it, and I always got the SelectedItem to be the one selected in salutation2. I double-checked every location were I was storing the values, in case I forgot to change the field name after copy/pasting. But everything was correct, as far as I could tell. I even checked the values submitted by the browser, they were also correct.

Finally, it hit me: The ListItem has a Selected property, and it is used to find the RadioButtonLists SelectedItem property. And since I reused the items, the first list parses its items on postback, sets the appropriate ListItem's Selected property to true. Same thing happens with the second RadioButtonList. And since the ListItems are used in both lists, the last one wins.

So, I changed my code to look like this:

ListItem[] items = new ListItem[2];
items[0] = new ListItem(this.GetString("salutation.Mister"), "Mr");
items[1] = new ListItem(this.GetString("salutation.Misses"), "Mrs");
this.salutation.Items.AddRange(items);
items = new ListItem[2];
items[0] = new ListItem(this.GetString("salutation.Mister"), "Mr");
items[1] = new ListItem(this.GetString("salutation.Misses"), "Mrs");
this.salutation2.Items.AddRange(items);

Now everything works as it should. So next time, be careful when reusing your ListItems!

Tags: , , ,

Development

Month List

Impressum (for the Germans)

Christoph Herold

Dieses Weblog wird bereitgestellt und verwaltet durch

Christoph Herold
Ignaz-Semmelweis-Str. 37
41540 Dormagen
Deutschland

Sie erreichen mich unter christoph.herold@coeamyd.net.