0

I have a drop-down as follows

<asp:Label runat="server" Text="Available Items"></asp:Label>
<asp:DropDownList runat="server" ID="ddItems"  />

Here is how data is populated in this dropdown.

protected void Page_Load(object sender, EventArgs e)
        {
            this.ddItems.Items.Add(new ListItem("first item", "1"));
            this.ddItems.Items.Add(new ListItem("second item", "2"));
            this.ddItems.Items.Add(new ListItem("third item", "3"));
            this.ddItems.SelectedIndex = -1;
        }

Since SelectedIndex is set to -1, I expect no items to be selected but first item is showing up in the drop down.

enter image description here

What am I doing wrong?

Pelle
  • 2,755
  • 7
  • 42
  • 49
whoami
  • 1,689
  • 3
  • 22
  • 45
  • 1
    Wouldn't you have an item in the dropdown labelled 'please select' (or some other message) to indicate nothing is selected? – Paulj Oct 20 '16 at 20:29

1 Answers1

1

-1 does not refer to a position in the list, therefore you need to add an item with default text or empty string.

Protected void Page_Load(object sender, EventArgs e)
    {
        // You can set the first list item text to empty string as well
        this.ddItems.Items.Add(new ListItem("select an item", ""));
        this.ddItems.Items.Add(new ListItem("first item", "1"));
        this.ddItems.Items.Add(new ListItem("second item", "2"));
        this.ddItems.Items.Add(new ListItem("third item", "3"));

        //This is no longer required as the default selected index is 0
        this.ddItems.SelectedIndex = 0;
    }
umutesen
  • 2,523
  • 1
  • 27
  • 41