Validate DropDownList Using Required Field Validator Asp.Net

This post explains How to Validate DropDownList Using RequiredFieldValidator In Asp.Net when either Dropdown is populated using SqlDataSource or when Drop Down is populated using List Items.

Place one dropdown list, button and requiredfieldvalidator controls in design view of page and add list items in HTML source of page as mentioned below.

   1:  <asp:DropDownList ID="ddlLanguage" runat="server">
   2:  <asp:ListItem>--Select--</asp:ListItem>
   3:  <asp:ListItem>C#</asp:ListItem>
   4:  <asp:ListItem>VB</asp:ListItem>
   5:  <asp:ListItem>Java</asp:ListItem>
   6:  </asp:DropDownList>


Set ControlToValidate, InitialValue, Error Message properties of required field validator as follows.

   1:  <asp:RequiredFieldValidator ID="rfvDdl" runat="server" 
   2:     ControlToValidate="ddlLanguage" 
   3:     ErrorMessage="Please Select a Language" 
   4:     InitialValue="--Select--" 
   5:     SetFocusOnError="True">
   6:  </asp:RequiredFieldValidator>


If dropdownlist is getting populated by SqlDataSource or ObjectDataSource at runtime then we need to set AppendDataBoundItems property of dropdown to true and add one list item at 0 or -1 index in Page_Load event of page.

   1:  <asp:DropDownList ID="ddlProducts" runat="server" 
   2:          AppendDataBoundItems="True" 
   3:          DataSourceID="SqlDataSource1" 
   4:          DataTextField="ProductName" 
   5:          DataValueField="ProductID">
   6:  </asp:DropDownList>
   7:   
   8:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
   9:          ConnectionString="<%$ ConnectionStrings:TestDbConnectionString %>" 
  10:          SelectCommand="SELECT [ProductName], [ProductID] FROM [Products]">
  11:  </asp:SqlDataSource>
  12:   
  13:  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
  14:          ControlToValidate="ddlProducts" 
  15:          ErrorMessage="Please select a product" 
  16:          InitialValue="0" SetFocusOnError="True">
  17:  </asp:RequiredFieldValidator>


Write following code in Page_Load Event in code behind.

protected void Page_Load(object sender, EventArgs e)
    {
        ddlProducts.Items.Insert(0,new ListItem("Choose Product","0"));
    }


Build and run the code.

If you like this post than join us or share

0 comments:

Find More Articles