user3470441 user3470441 - 27 days ago 11
HTML Question

ASP.NET - How to have a placeholder value for a data binded dropdownlist?

I am trying to have a placeholder value inside of a drop down list. The drop down list should be a list of stores like Walmart, Kmart, and so on. However, I want the first value item in the list to say "Select a Store." The problem is that I am getting the list of stores from a database table and binding it to the drop down list. So right now, the drop down list displays: Walmart, Kmart, Hmart. I want it to display: Select a Store, Walmart, Kmart, Hmart.
Note: I am using ASP.NET C#.

HTML:

<asp:DropDownList ID="ddlStore" class="btn btn-primary dropdown-toggle" runat="server" AutoPostBack="true" Width="80%" OnSelectedIndexChanged="ddlStore_SelectedIndexChanged">
</asp:DropDownList>


Code-behind:

public void getStores()
{
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.CommandText = "dbo.Store_Select";

DataSet ds;
ds = conn.GetDataSetUsingCmdObj(objCommand);
ddlStore.DataSource = ds.Tables[0];

if (ds.Tables[0].Rows.Count == 0)
{
/*No Store to display*/
}
else
{
foreach (DataRow current_row in ds.Tables[0].Rows)
{
ddlStore.DataTextField = "Store_Name";
ddlStore.DataValueField = "Store_ID";
}
}
ddlStore.DataBind();
}


Thank You.

Answer

After the binding the DB data to the control ddlStore.DataBind(); you can simply insert the ListItem using

ddlStore.Items.Insert(0, new ListItem("Select a store", ""));

Full method:

public void getStores()
{
    objCommand.CommandType = CommandType.StoredProcedure;
    objCommand.CommandText = "dbo.Store_Select";

    DataSet ds;
    ds = conn.GetDataSetUsingCmdObj(objCommand);
    ddlStore.DataSource = ds.Tables[0];

    if (ds.Tables[0].Rows.Count == 0)
    {
    /*No Store to display*/
    }
    else
    {
        foreach (DataRow current_row in ds.Tables[0].Rows)
        {
            ddlStore.DataTextField = "Store_Name";
            ddlStore.DataValueField = "Store_ID";
        }
    }
    ddlStore.DataBind();
    ddlStore.Items.Insert(0, new ListItem("Select a store", ""));
 }
Comments