Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a RequiredFieldValidator to DropDownList control?

I have a DropDownList binded with aSqlDataSource to display the values from the database.

I am unable to validate using a RequiredFieldValidator.

like image 801
user242375 Avatar asked Feb 17 '10 12:02

user242375


People also ask

How to validate DropDownList in asp net?

To use ASP.NET validator with DropDownList control, set the ID of the DropDownList as the value of the ControlToValidate property of the validator. Executing the above code will validate the DropDownList control values on every form submit before post back occurs as given below.

Which property is used for adding values in DropDownList?

After dragging, our web form looks like the below. Now, to add items to the list, visual studio provides Items property where we can add items. The property window looks like this.


1 Answers

For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" /> 

Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.

If databinding you will need to insert the "Please select" value afterwards as follows

this.ddl1.Items.Insert(0, "Please select"); 
like image 195
Fishcake Avatar answered Nov 09 '22 22:11

Fishcake