0

I have a DropDownList with values

1.--select one--
2.one
3.two
4.three

Now I want to know whether user have changed the default value of DropDownList or not.Currently I am hard coding the values like this

if(ddlCountry.SelectedItem.Text !="--Select One--")

I don't think this is a good practice as I have a lot of DropDownLists like this in my page and some will be binded dynamically..Can any one give me the best practice?

4

4 回答 4

3

When I was faced with a similar problem, I used the Value property for all other items BUT the default.

Then I would check

if (!String.IsNullOrEmpty(dropDown.SelectedItem.Value))
{  }

This assumes the default value might not be the first on the dropdown - which it is in the majority of cases, but other people have already got that case covered. ;)

于 2013-08-06T06:17:43.943 回答
1

What about using

if(ddlCountry.SelectedIndex != 0)
于 2013-08-06T06:15:32.153 回答
1

Not sure, if this is the best practice, but default values are the first itmes in DropDownLists hence this check: ddlCountry.SelectedIndex > 0 should suffice for all dropdowns.

于 2013-08-06T06:15:44.310 回答
1

What others have said should be good enough, but it would be even better if you give your default option a value - say -1 or Select or something like that and then check -

if(ddlWithDefault.SelectedItem.Value != "-1" && ddlWithDefault.SelectedItem.Value.ToLower() != "select")
{
   // Do your thing here...
}
于 2013-08-06T06:20:10.260 回答