In ASP.NET we need to validate DropDownList controls. But validating the DropDownList control with RequiredFieldValidator is not a straight forward as validating a TextBox control with RequiredFieldValidator. It requires little extra work.
Following are the steps for validating a DropDownList with RequiredFieldValidator
Step 1: Create a DropDownList control
Step 2: Add a RequiredFieldValidator
Step 3: Add an Initial Value Property to RequiredFieldValidator
Complete Code
Following are the steps for validating a DropDownList with RequiredFieldValidator
Step 1: Create a DropDownList control
1: <asp:DropDownList ID="ddlFruit" runat="server" Height="22px" Width="200px">
2: <asp:ListItem>- Select -</asp:ListItem>
3: <asp:ListItem>Apple</asp:ListItem>
4: <asp:ListItem>Orange</asp:ListItem>
5: <asp:ListItem>Banana</asp:ListItem>
6: <asp:ListItem>Pineapple</asp:ListItem>
7: </asp:DropDownList>
Step 2: Add a RequiredFieldValidator
1: <asp:RequiredFieldValidator ID="rfvFruit" runat="server" ErrorMessage="Select a Fruit"
2: ControlToValidate="ddlFruit" ValidationGroup="Add">
3: </asp:RequiredFieldValidator>
Step 3: Add an Initial Value Property to RequiredFieldValidator
1: InitialValue="- Select -"
Complete Code
1: <table style="width: 100%;">
2: <tr>
3: <td align="right">
4: Fruit:
5: </td>
6: <td style="vertical-align: middle;">
7: <asp:DropDownList ID="ddlFruit" runat="server" Height="22px" Width="200px">
8: <asp:ListItem>- Select -</asp:ListItem>
9: <asp:ListItem>Apple</asp:ListItem>
10: <asp:ListItem>Orange</asp:ListItem>
11: <asp:ListItem>Banana</asp:ListItem>
12: <asp:ListItem>Pineapple</asp:ListItem>
13: </asp:DropDownList>
14: <asp:RequiredFieldValidator ID="rfvFruit" runat="server" ErrorMessage="Select a Fruit"
15: ControlToValidate="ddlFruit" InitialValue="- Select -" ValidationGroup="Add">
16: </asp:RequiredFieldValidator>
17: </td>
18: </tr>
19: <tr>
20: <td>
21: </td>
22: <td>
23: <asp:Button ID="btnAdd" runat="server" Text="Save" ValidationGroup="Add" Width="70px" />
24: </td>
25: </tr>
26: </table>
Comments
Post a Comment