Monday 23 June 2014

how to set required field validator with DropDownList in Asp.Net






Description:-

In this example we explain that how to set RequireField Validator for Dropdownlist and Listbox in asp.net or how to validate dropdownlist and listbox in asp.net.

We all know that in any website and web application all developer must need to validate Dropdownlist and listbox in many web forms because of that is the basic requirement in any website.

The main point must keep in mind when you have to set RequireField validator for the Dropdownlist or Listbox is that you have to set InitialValue="0" property of the RequireField validator and in Dropdownlist put this line <asp:ListItem Value="0">--Select--</asp:ListItem>


 Create Nested Gridview in asp.Net Nested Gridview example

File Upload Example in MVC4 Upload File and bind to Gridview

Read/Write File in asp.net Read/write file using c#


Code:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="validatedropdownlist.aspx.cs"
    Inherits="validatedropdownlist" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Validate ListBox and DropDown List using Required Field Validator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="lstboxCountry" runat="server" Width="200px" SelectionMode="Multiple">
            <asp:ListItem Value="1">India</asp:ListItem>
            <asp:ListItem Value="2">Pakistan</asp:ListItem>
            <asp:ListItem Value="3">Austalia</asp:ListItem>
            <asp:ListItem Value="4">Japan</asp:ListItem>
            <asp:ListItem Value="5">UK</asp:ListItem>
            <asp:ListItem Value="6">USA</asp:ListItem>
           
        </asp:ListBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="lstboxCountry"
            InitialValue="" runat="server" ErrorMessage="selection of country is required"></asp:RequiredFieldValidator>
    </div>
    <br />
    <div>
        <asp:DropDownList ID="drpdwnCity" runat="server" Width="200px">
            <asp:ListItem Value="0">--Select--</asp:ListItem>
            <asp:ListItem Value="1">Ahmedabad</asp:ListItem>
            <asp:ListItem Value="2">Rajkot</asp:ListItem>
            <asp:ListItem Value="3">Surat</asp:ListItem>
            <asp:ListItem Value="4">Baroda</asp:ListItem>
            <asp:ListItem Value="5">Junagadh</asp:ListItem>
            <asp:ListItem Value="6">Bhavanagar</asp:ListItem>
           
        </asp:DropDownList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="drpdwnCity"
            InitialValue="0" runat="server" ErrorMessage="selection of city is required"></asp:RequiredFieldValidator>
    </div>
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </form>
</body>
</html>


0 comments:

Post a Comment