简体   繁体   中英

Determining the index of a list based on another list and vice versa, solutions in C#/VB.NET or JavaScript are welcome

Suppose you have list 1 (ilist1) and list 2 (ilist2) both lists have 3 items.

At index 0 item1 which has text "-- Select --" At index 1 item2 which has text "Yes" At index 2 item3 which has text "No"

Both lists have identical items. I would like to know if it is possible to have the selection of list one be "Yes" and the selection of list two be "No" and vice versa using SelectedIndexChanged or something of the sort.

For example: ilist1 = --Select-- ilist2 = --Select--

User changes ilist1 to No: ilist1 = No ilist2 = Yes (can be done on Index changed)

Now if the user selects No on ilist2, ilist1 will change to Yes without user intervention SO ilists are now: ilist1 = Yes ilist2 = No

In other wants I want to be able to do the following for both lists without having to run into an infinite loop (I want the list to stop changing indexes when the user has stopped selecting).

protected void IndexChanged(object sender, EventArgs e)
{
    ilist1 = (DropDownList)sender;
    if (ilist1.SelectedIndex == 0) { }
    else if (ilist1.SelectedIndex == 1) {
        ilist2.SelectedIndex = 2;
    }
    else if (ilist1.SelectedIndex == 2){
        ilist2.SelectedIndex = 1;
    }
}

Let me know if this is possible, Thank You Guys

A trivial solution would be to add an extra condition in the else if's to not change the index if it is already correct:

protected void IndexChanged(object sender, EventArgs e)
{
    ilist1 = (DropDownList)sender;
    if (ilist1.SelectedIndex == 0) { }
    else if (ilist1.SelectedIndex == 1 && ilist2.SelectedIndex != 2) {
        ilist2.SelectedIndex = 2;
    }
    else if (ilist1.SelectedIndex == 2 && ilist2.SelectedIndex != 1){
        ilist2.SelectedIndex = 1;
    }
}

Will provide the recipe and sort of pseudo code:

  1. Set AutoPostBack =true on both lists
  2. On SelectedIndexChanged do something like:

     protected void IndexChanged(object sender, EventArgs e) { DropDownList theList = (DropDownList)sender; if(theList.ID=="Id of list 1") { if(theList.SelectedValue=="No") list2.Items.FindByValue("Yes").Selected=true; } else //list2 fired the indexchanged event { if(theList.SelectedValue=="Yes") list1.Items.FindByValue("No").Selected=true; } } 

Code above may not be right as far as setting the selections the way you want them; the important thing to note is the use of FindByValue and Selected=true . If the indexes of the items in the list ever change for some reason; you won't have to modify your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM