Validating a DropDownList Using Required Field Validator in Asp.Net C# VB.Net

When we bind data into a DropDownList Control we found that the first ListItem getting selected by default. If you want to force to select an Item of a DropDownList rather than default selection you have to add a ListItem like “–Please Select–” as an Item. In this scenario if you add a Required Field Validator, the validator can not validate the DropDownList. To do that you have to mention Required Field Validator InitialValue property =”0″. The example is given below:

Objective/Outcome:
Validating a DropDownList Using Required Field Validator in Asp.Net C# VB.Net

Sample Code to validate DropDownlist:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Value="0">--Select Month--</asp:ListItem>
    <asp:ListItem Value="1">January</asp:ListItem>
    <asp:ListItem Value="2">February</asp:ListItem>
    <asp:ListItem Value="3">March</asp:ListItem>
    <asp:ListItem Value="4">April</asp:ListItem>
    <asp:ListItem Value="5">May</asp:ListItem>
    <asp:ListItem Value="6">June</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="DropDownList1" InitialValue="0"  runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
 <br />
 <hr />
 <asp:Button ID="Button1" runat="server" Text="Validate DropDownList" /> 
</asp:Content>

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

     

*