“DropDownList.SelectedIndex = -1” problem

asp.netdrop-down-menuwebforms

I just want an ASP.NET DropDownList with no selected item. Setting SelectedIndex to -1 is of no avail, so far. I am using Framework 3.5 with AJAX, i.e. this DropDownList is within an UpdatePanel.
Here is what I am doing:

    protected void Page_Load (object sender, EventArgs e)
    {
        this.myDropDownList.SelectedIndex = -1;
        this.myDropDownList.ClearSelection();

        this.myDropDownList.Items.Add("Item1");
        this.myDropDownList.Items.Add("Item2");
    }

The moment I add an element in the DropDown, its SelectedIndex changes to 0 and can be no more set to -1 (I tried calling SelectedIndex after adding items as well)… What I am doing wrong? Ant help would be appreciated!

Best Solution

Bare in mind myDropDownList.Items.Add will add a new Listitem element at the bottom if you call it after performing a DataSource/DataBind call so use myDropDownList.Items.Insert method instead eg...

myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();

myDropDownList.Items.Insert(0, new ListItem("Please select", ""));

Will add the 'Please select' drop down item to the top.

And as mentioned there will always be exactly one Item selected in a drop down (ListBoxes are different I believe), and this defaults to the top one if none are explicitly selected.

Related Question