Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an empty first entry do an <asp:DropDownList>?

I have a dropdown, I have a datasource, I have AutoPostBack set to true.
I want to add a first entry to the datasource that says something like "--- select country ---" and selecting this entry won't cause postback.
This feels like it should be easy to do, yet I can't seem to be able to find a good solution.
Thanks.

like image 935
vitule Avatar asked Jan 13 '09 15:01

vitule


People also ask

How can I select multiple values from a drop-down list in asp net?

The ASP.NET Core MultiSelect Dropdown is a quick replacement for the HTML select tag for selecting multiple values. HTML MultiSelect Dropdown is a textbox control that allows the user to type or select multiple values from a list of predefined options.

What is cascading DropDownList in asp net?

A cascading drop-down list is a series of dependent DropDownList controls in which one DropDownList control depends on the parent or previous DropDownList controls. The items in the DropDownList control are populated based on an item that is selected by the user from another DropDownList control.

What is AutoPostBack in DropDownList in asp net?

AutoPostBack of the ASP.Net DropDownList control provides the functionality to allow the server side post back event of the web page when user Select the DropDownlist Item from control while running programm.


1 Answers

In your aspx page (the important part is handling the DataBound event and setting CausesValidation="true" to force validation of a drop down list):

<asp:DropDownList ID="ddlCountries" runat="server" DataSourceID="dsCountries" AutoPostBack="true" OnDataBound="ddlCountries_DataBound" CausesValidation="true" />
<asp:RequiredFieldValidator ID="rfvCountries" runat="server" ControlToValidate="ddlCountries" Display="Dynamic" ErrorMessage="Please select a country." />

In your codebehind (it is important that the value of the inserted item is String.Empty for the required field validator to work!):

protected void ddlCountries_DataBound(Object sender, EventArgs e)
{
ddlCountries.Items.Insert(0, new ListItem("--- select country ---", String.Empty));
}

Note: If you don't want the validator's message to display, set the "Display" property to "None".

like image 200
Daniel Schaffer Avatar answered Sep 24 '22 23:09

Daniel Schaffer