xorpower
xorpower

Reputation: 18973

How to verify dropdownlist values are selected?

My ASP.NET application has a requirement, where if a user selects a country from a country dropdownlist and if a country has a state (which usually every country has!), then a validation needs to be written down that checks that the state is selected.

If no state exists (for selected country, from country dropdownlist) then the validation should skipped and no error/validation message should thrown up.

I need to validate the state selection on the click of the button

Please guide me!

Code

   private void LoadCountry()
    {
        Country objcountry= new Country ();
        int iSuccess = 0;
        DataSet dsCtry= new DataSet();
        dsCtry= objcountry.LoadCountry();
        if (iSuccess == 0)
        {

            ddlCtry.DataSource = dsCtry.Tables[0];
            ddlCtry.DataTextField = "COUNTRY";
            ddlCtry.DataValueField = "COUNTRY";
            ddlCtry.DataBind();
            ddlCtry.Items.Insert(0, new ListItem("-- Select --", ""));
        }
    }

Thanks!

Upvotes: 0

Views: 1976

Answers (3)

Neelam
Neelam

Reputation: 1068

write a javascript function

            if (document.getElementById('ddlcountry').value == '--Select--' || document.getElementById('ddlcountry').value == '0')
            {   
                 alert("Please select a Country");
                document.getElementById('ddlcountry').focus();
                return false;
            } 
           else
           {
            if (document.getElementById('ddlstate').value == '--Select--' || document.getElementById('ddlstate').value == '0')
            {   
                 alert("Please select a State");
                document.getElementById('ddlstate').focus();
                return false;
            } 
            }

Upvotes: 1

Kent
Kent

Reputation: 2960

You should use two dropdownlists

The first one is for countries. The second is for states of country.

When user select one county, you get states of that country and bind into the second dropdownlist. And base on the size of the second dropdownlist, you can validate the selected state.

Hope this helps ^^

Upvotes: 0

Samir Adel
Samir Adel

Reputation: 2499

You have 2 options:

  1. When the country drop down list selected index change you check if the state drop down list contain items and if contain enable the validator and if there is no item disable the required field validator.

  2. To make the validation client side using jquery.

Upvotes: 0

Related Questions