asp.netdrop-down-menu

How to add an item at the top of a dropdownlist in ASP.NET


Why is the dropdown not showing my blank item first? Here is what I have:

drpList.Items.Add(New ListItem("", ""))

With drpList
    .DataSource = myController.GetList(userid)
    .DataTextField = "Name"
    .DataValueField = "ID"
    .DataBind()
End With

I am binding to a Generic List, could this be the culprit?


Solution

  • After your databind, add the following lines of code:

    drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
    drpList.SelectedIndex = 0;
    

    The syntax for the ListItem() parameters is display text first, and then the value, in case you want to insert a non-blank entry.