Search code examples
c#dropdownlistfor

Adding to dropdown list that is linked to a SqlDataSource


I have a dropdown list that is linked to a SQL table. The table does not have a null row so when I load the dropdown list it shows the first entry in the SQL table. I need the first entry to the dropdown list to be blank. I tried the below but it is still showing the first item from the SQL table.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        DropDownList33.Items.Insert(0, new ListItem(" ", " "));
    }
}

Solution

  • SET the AppendDataBoundItems=true and then add your empty item to the ListItem like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DropDownList33.AppendDataBoundItems = true;
            DropDownList33.Items.Insert(0, new ListItem(String.Empty, String.Empty));
            DropDownList33.SelectedIndex = 0;
        }
    }