Dropdowns filled with same list item

[亡魂溺海] 提交于 2019-12-11 01:19:08

问题


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:


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'.




回答2:


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)?




回答3:


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!




回答4:


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




回答5:


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...



来源:https://stackoverflow.com/questions/428001/dropdowns-filled-with-same-list-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!