0

DropDownList control is returning the wrong item.

My code performs a specific action with the SelectedItem when DropDownList.SelectedValue = -1.

When testing the code, I pick item A at index = 2. The resulting DropDownList.SelectedItem = "A". Good so far.

But I pick item B at index = 3. The resulting DropDownList.SelectedItem = "A". According to the debugger, DropDownList.SelectedIndex = 2 in both cases.

What causes the SelectedIndex to always take on the same value?

Note: When I pick items C through Z, they return the proper SelectedText and SelectedIndex.

if(Int32.Parse(dropdown.SelectedValue).Equals(-1))
{
    // Do something with the selected item
    DoThis(dropdown.SelectedItem.ToString());
}
Spencer H
  • 653
  • 3
  • 12
  • 30
  • It should be `dropdown.SelectedIndex == -1` – Rahul Jul 29 '16 at 18:36
  • 1
    Let's see what your doing in Page_Load(). – Rick S Jul 29 '16 at 18:37
  • @RickS Page_Load() shouldn't make much of a difference. The DoThis() saves a value to my DB, so the value should be OK. Value of both items is the same. But index is being returned as the same as well. – Spencer H Jul 29 '16 at 18:38
  • 1
    I was asking because many times on postback the dropdown list is repopulated therefore you would see the first entry always selected. – Rick S Jul 29 '16 at 18:43
  • @RickS Good point - I realized I do repopulate my dropdown list in Page_Load(). Everything is reinitialized in the same order with the same indices. So wouldn't the proper index be selected still? – Spencer H Jul 29 '16 at 18:51
  • No, you need to wrap the code in `if (!IsPostBack)` – Rick S Jul 29 '16 at 18:53
  • @RickS I have this: if (!IsPostBack) { PopulateDropDownList(); } – Spencer H Jul 29 '16 at 18:55
  • I updated the original post: Note: When I pick items `C` through `Z`, they return the proper `SelectedText` and `SelectedIndex`. – Spencer H Jul 29 '16 at 19:02
  • @RickS Does it make a difference if the PopulateDropDownList is called _after_ the code block in the post? I do this update the dropdown list, but I'm guessing it has no impact on the error. – Spencer H Jul 29 '16 at 19:24

1 Answers1

4

When several items of a DropDownList have the same value, selecting any of them will turn out as if the first item with that value was selected. You should modify the duplicate values to make each one unique.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146