Friday, October 12, 2012 Required Field Validator with DropDownList

Today I want to share a very simple stuff That I learned while working, its kind of a silly learning, but hopefully will help someone someday. I want to make sure that a DropDownList is been selected before submitting a form. In we have a control for validation name “RequiredFieldValidator”, till now I have seen using this with only textbox. Below an example is given.

<asp:TextBox runat="server" ID="txtNumber" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ForeColor="red" runat="server" ID="rfvNewTrackingNumber"
ControlToValidate="txtNumber" ErrorMessage="* Please type number">

But we can actually use this required field validator with DropDownList as well. Below another example is given for using with DropDownList

<asp:DropDownList runat="server" ID="ddlMethods" AppendDataBoundItems="True" Width="205px">
<asp:ListItem Value="0">Select Method</asp:ListItem>
<asp:RequiredFieldValidator ForeColor="red" runat="server" ID="rfvNewMethod"
ControlToValidate="ddlMethods" ErrorMessage="* Please select method" InitialValue="0">

Note that in ListItem we have assigned Value=0 and in RequiredFieldValidator InitialValue=0 that is the main trick. If you have binding code in c# please make sure you also Set DataValueField.

Until next time.

No comments:

Post a Comment