ASP.NET ListItems are by reference
I was trying to add yes / no values to three dropdowns on my ASP.NET page. We’re using custom drop down controls, so I needed to add the dropdown items in code behind. Always liking to be efficient in my code and make it pretty, I used this:
ListItem listItem;
listItem = new ListItem(”No”, “0″);
DropDown1.Items.Add(listItem);
DropDown2.Items.Add(listItem);
DropDown3.Items.Add(listItem);
listItem = new ListItem(”Yes”, “1″);
DropDown1.Items.Add(listItem);
DropDown2.Items.Add(listItem);
DropDown3.Items.Add(listItem);
Later, I’m loading my values from the database like this:
DropDown1.SelectedValue = data.IsBool1 ? "1" : "0";
DropDown2.SelectedValue = data.IsBool2 ? "1" : "0";
DropDown3.SelectedValue = data.IsBool3 ? "1" : "0";
However, it turns out that when you do it this way, whenever DropDown3 is changed, the same value will be chosen for DropDown1 and DropDown2 as well. ASP.NET keeps track of the ListItem objects by reference.
The correct way to do this should be:
DropDown1.Items.Add(new ListItem("No","0"));
DropDown1.Items.Add(new ListItem("Yes","1"));
DropDown2.Items.Add(new ListItem(”No”,”0″));
DropDown2.Items.Add(new ListItem(”Yes”,”1″));
DropDown2.Items.Add(new ListItem(”No”,”0″));
DropDown2.Items.Add(new ListItem(”Yes”,”1″));
I guess this is technically less lines of code, but I was thinking creating new ListItem objects each time would be less efficient than my original code. Not that a nanosecond will make any perceivable difference.
I guess it’s refactoring time!