john smith john smith - 1 month ago 16
ASP.NET (C#) Question

why an item is selected in the dropdown?

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?

Answer

-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;
    }
Comments