select same index in list box

2020-05-01 10:25发布

问题:

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.