views:

202

answers:

5

I have a Gridview in which i have two templatefields of dropdownlist. I bound them on runtime with same list item.

li = new listitem ("1","1");
dl1.items.add(li);
dl2.items.add(li);

li = new listitem ("2","2");
dl1.items.add(li);
dl2.items.add(li);

li = new listitem ("3","3");
dl1.items.add(li);
dl2.items.add(li);

dl1.selectedvalue = "2";
dl2.selectedvalue = "3";

After executing above, dl1 & dl2 both show me "3" as selected value. Why?

I know the work around of using 2 different listitems while binding but i wanna know why the above happens?

+1  A: 

You have to instantiate each list item for each drop down list.

ListItem li1 = new ListItem("1","1");
dl1.items.add(li1);

ListItem li2 = new ListItem("1", "1");
dl2.items.add(li2);

Edit: Jon described what I want to mean. You have only one object that has a value. So don't expect different values for each drop down list.

When you set dl1 to "3" then both of them will get the same value because both drop down lists reference to same object!

yapiskan
Please read my question completely : I know the work around of using 2 different listitems while binding but i wanna know why the above happens?
Samiksha
See my updated answer.
yapiskan
+1  A: 

I would think it would be a ref vs value problem. I am sure both d1 and d2 would be pointing to the same spot in memory if the are added from the same list item...

cgreeno
+3  A: 

Looking at just the last part of the code: you've got a single list item, and it's appearing in two different lists. But it's still one object. How would you expect one object to have two different values for a single property (SelectedValue)?

Jon Skeet
+1  A: 

the listitem is being shared among the two drop downs. when you set the selected value for one of the drop downs it sets the list item as being selected. since the listitem is being shared it's selected in both drop downs

SquidScareMe
by the way, sorry for the terse answer. i was typing from a cell phone.
SquidScareMe
+2  A: 

The ListItem class has a property "Selected" which marks if the item is selected. I haven't checked the DDL SelectedValue property to see what it does, but my guess is that the ListItem.Selected property is being set to true, and since you are using the same object in both drop-down lists, it is being marked as 'selected' in both.

I'm sure if this was a multi-select list, both "2" and "3" would be marked as 'selected'.

Jay S