Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a default "Select" option to this ASP.NET DropDownList control?

I am a new ASP.NET developer and I am trying to learn Linq-To-Entities. I am trying to bind a DropDownList with the Linq statement for retrieving the list of status in the Status Entity. Everything is working fine. However, I am trying now to add "Select" option to the DropDownList but It doesn't work with me. Could you please tell me how to fix this?

ASP.NET Code:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

Code-Behind:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.Items.Add(new ListItem("Select", "0", true));
            bindStatusDropDownList();
        }
    }

private void bindStatusDropDownList()
    {
        Status status = new Status();
        DropDownList1.DataSource = status.getData();
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataTextField = "Description";
        DropDownList1.DataBind();
    }

UPDATE:

I also tried to do in the markup set of the DropDownList but it did not work too with me

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
            </asp:DropDownList>
like image 612
user3107976 Avatar asked Dec 20 '13 09:12

user3107976


2 Answers

The reason it is not working is because you are adding an item to the list and then overriding the whole list with a new DataSource which will clear and re-populate your list, losing the first manually added item.

So, you need to do this in reverse like this:

Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();

// Then add your first item
DropDownList1.Items.Insert(0, "Select");
like image 82
Belogix Avatar answered Sep 17 '22 15:09

Belogix


Although it is quite an old question, another approach is to change AppendDataBoundItems property. So the code will be:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                  OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                  AppendDataBoundItems="True">
     <asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
</asp:DropDownList>
like image 37
Konstantin Vasilev Avatar answered Sep 20 '22 15:09

Konstantin Vasilev