select same index in list box

大城市里の小女人 提交于 2019-12-20 07:11:28

问题


I am making a website in asp.net and I have 2 list boxes:

lbxPlayer1 and lbxPlayer2

lbxPlayer1.Items.Add("bob");
lbxPlayer1.Items.Add("jack");
lbxPlayer1.Items.Add("sam");

lbxPlayer2.Items.Add("fred");
lbxPlayer2.Items.Add("brian");
lbxPlayer2.Items.Add("dave");

they have both been populated with the same amount of values and i would like it so that when one of the lists is clicked the other list will select the same index.

how do i do this? i assume the code would be in the lbxPlayer1_SelectedIndexChanged event?

so when i click on "jack" i want "Brian" to also be selected.


回答1:


Use the SelectedIndex property:

int index = lbxPlayer1.SelectedIndex;
if(lbxPlayer2.Items.Count > index)
   lbxPlayer2.SelectedIndex = index;

If SelectionMode is Multiple:

for (int i = 0; i < lbxPlayer2.Items.Count; i++)
{ 
    if(i >= lbxPlayer1.Items.Count)
        lbxPlayer2.Items[i].Selected = false;
    else
        lbxPlayer2.Items[i].Selected = lbxPlayer1.Items[i].Selected;
}

Update

well it tried it and nothing happened also tried this and nothing happens either lbxPlayer2.SelectedIndex = lbxPlayer1.SelectedIndex;. The dayabinding is getting done in the pageload event (which i cannot change), which i > believe is always o

Only databind them if(!IsPostBack) since ViewState will retain items across postbacks. So i assume that this event is never triggered because you rebind the ListBoxes on postbacks.



来源:https://stackoverflow.com/questions/15180787/select-same-index-in-list-box

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