Monday, September 29, 2008

Using RequiredFieldValidator with DropdownList Asp.Net

You may have used RequiredFieldValidator with Text controls, but if you wnat to use it with DropDownList controls, you need to do some little extra work. Here is the trick.Step 1: Create an DropDownList

Step 2: Drag and RequiredFieldValidator. Set it’s ControlToValidate property to the DropDownLis’s object.

Step 3: Fill some items in the DropDownList. Add a first item as “Select”. This will indicate the user that he should select an option.

Step 4: Now set the RequiredFieldValidator’s “InitialValue” property to “Select”.

Now all of your code should look like this :

<asp:DropDownList ID=”cmbCountry” runat=”server”>
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>India</asp:ListItem>
<asp:ListItem>USA</asp:ListItem>
<asp:ListItem>Canada</asp:ListItem>
</asp:DropDownList>

<asp:RequiredFieldValidator ID=”rqCountry” runat=”server” ErrorMessage=”*” SetFocusOnError=”True” ControlToValidate=”cmbCountry” InitialValue=”Select”></asp:RequiredFieldValidator>

Now you are all set to go and test it.


Click here to download Source code

No comments: