Loading ...

How to Validate DropdwonList in asp.net

 /5
0 (0votes)

 Validate DropdwonList

Hi

Today im gonna tell  you how to validate a dropdownlist

 Suppose if you want to validate a dropdownlist where you want that if the user doesnt select any value he/she should get an error message .This is how you can validate it.

Her i want that user must select a country from the dropdownlist else he/she would get an error message

Select a Country:

 <asp:DropDownList ID="ddl_Country" runat="server" align="left" Width="250px" ></asp:DropDownList>

<asp:RequiredFieldValidator ID="rfvddl_Country" runat="server" Display="Static" ErrorMessage="Select a country!" ControlToValidate="ddl_Country"  InitialValue="-1"></asp:RequiredFieldValidator>

This how i'm binding the data in the code behind.

  private void PopulateCountries()
        {
            CountryCollection countries = new CountryCollection();
            ddl_Country.DataSource = countries.FindAll();
            ddl_Country.DataTextField = "CountryName";
            ddl_Country.DataValueField = "CountryID";

            ddl_Country.DataBind();

            ddl_Country.Items.Insert(0,new ListItem("Select Country","-1"));

        }

If you will not select any country you will get an error message "Select a country".

Hope it will be of some help.

Comments (no comments yet)

Top Posts