Samrikan
Samrikan

Reputation: 63

Dropdown list default value

So I have populated my dropdown list using a table adapter object, it displays lists of cities. How do I make a default value? for example "Select your city"

This is the dropdown list:

<asp:DropDownList 
          ID="list_city" runat="server" DataSourceID="CityObject"
          DataTextField="city" class="form-control" DataValueField="ID">
 </asp:DropDownList>

Upvotes: 0

Views: 725

Answers (3)

Thomas Andre&#232; Wang
Thomas Andre&#232; Wang

Reputation: 3429

You can alter the control after you have bound with the OnDataBound. This is done pretty in the blind. so it might not work tight off the bat, but something along these lines should work.

Website.aspx

<asp:DropDownList
            ID="list_city" runat="server" DataSourceID="CityObject" OnDataBound="list_city_DataBound"
            DataTextField="city" class="form-control" DataValueField="ID">
</asp:DropDownList>

Website.aspx.cs

protected void list_city_DataBound(object sender, EventArgs e)
{
    list_city.Items.Insert(0, new ListItem("Select your city", "0"));
}

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 21795

You can use AppendDataBoundItems property like this:-

<asp:DropDownList ID="list_city" runat="server" DataSourceID="CityObject"
      DataTextField="city" class="form-control" DataValueField="ID" 
            AppendDataBoundItems="true">
   <asp:ListItem Selected="True" Text="Select Your City" Value="-1"></asp:ListItem>
</asp:DropDownList>

Upvotes: 2

Angus Chung
Angus Chung

Reputation: 1587

You can add the default value after your databind.

list_city.Items.Insert(0, new ListItem("Select your city", ""));
list_city.SelectedIndex = 0;

Upvotes: 0

Related Questions