views:

55

answers:

2

I have an ASP.NET 4 WebForm with 4 dropdowns in a table.

<table>
  <tr><td><asp:DropDownList ID='dd1' runat='server' /></td></tr>
  <tr><td><asp:DropDownList ID='dd2' runat='server' /></td></tr>
  <tr><td><asp:DropDownList ID='dd3' runat='server' /></td></tr>
  <tr><td><asp:DropDownList ID='dd4' runat='server' /></td></tr>
</table>

In the code behind I load these with items so they all match. Then I retrieve data from a database and call a method for each db record to set the dropdown's selected index.

int i = 0;
foreach (var rec in dataRecords) {
    switch (i) {
      case 0:
        SetDropDownValue(rec, dd1);
        break;
      case 1:
        SetDropDownValue(rec, dd2);
        break;
      case 2:
        SetDropDownValue(rec, dd3);
        break;
     case 3: ...
     case 4: ...
     default: ...
}
i++;

private void SetDropDownValue(DBRecord selectedRecord, DropDownList dl)
{
    string importantVal = selectedRecord.Field;
    var li = dl.Items.FindByValue(importanVal);
    dl.SelectedIndex = dl.Items.IndexOf(li);
}

Stepping through debugger the records are correct and the dropdownlist is the correct in the SetDropDownValue method.

As soon as dl.SelectedIndex = dl.Items.IndexOf(li); executes, all the previous dropdownlists' passed to the method have their selected index is updated too. So when the selected index of ddl2 is changed, ddl1 is changed to ddl2's new selected index. When ddl3 is updated, ddl1 & ddl2 are updated. When ddl4 is set, ddl1, ddl2, and ddl3 selected indexes are updated.

A: 

When I loaded the dropdowns I was doing something like this:

foreach (var dropDownOption in DropDownOptions) {
  ListItem li = new ListItem(dropDownOption.ValueField);
  dd1.Items.Add(li);
  dd2.Items.Add(li);
  ...
}

So all the ListItems where the same for each list.

To fix I had to create a new ListItem for each dropdown I was wanting to add to.

ListItem li = new ListItem(dropDownOption.ValueField);
dd1.Items.Add(li);
li = new ListItem(dropDownOption.ValueField);
dd2.Items.Add(li);
...
dr
A: 

Thanks a lot! Spent nearly two days of work of hunting this "bug" and finally found someone with the exactly the same problem. Made my day a happy one!

Hannes Fabian