How to add a RequiredFieldValidator to DropDownList control?

user242375 picture user242375 · Feb 17, 2010 · Viewed 144.4k times · Source

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

I am unable to validate using a RequiredFieldValidator.

Answer

Fishcake picture Fishcake · Feb 17, 2010

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");