Tuesday, 10 December 2013

How to set RequiredFieldValidator on DropDownList in ASP.NET?


Lets assume that we have a DropDownList named 'Gender' in our Registration Form and it is a required field so that user must select it. First we have to set the following DropDownList properties:

ID Gender
Items (Collection)...
  • Click on the Collection button then ListItem Collection Editor would be open as shown below:
  • Click on the Add button and set the ListItem properties as follows:
 
  • Click 'OK' and set the RequiredFieldValidator properties as follows:
ID Gender_Validator
ControlToValidate Gender
ErrorMessage Please select Gender
InitialValue 0

Now if user does not select either 'Male' or 'Female' then RequiredFieldValidator would generate an error message.

Code Snippet:
<asp:RequiredFieldValidator ID="Gender_Validator" runat="server" ControlToValidate="Gender" ErrorMessage="Please Select Gender" InitialValue="0"></asp:RequiredFieldValidator>

Demo:
Gender
Download Source Code

No comments:

Post a Comment