ASP.NET validate DropDownList control using VB.NET

Here, we will learn how to validate a DropDownList in ASP.NET.
  • 4781

You can use RequiredFieldValidator control with InitialValue as the default value for the DropDownList box. You can also validate the selected value of ASP. Net DropDownList control using RequiredFieldValidator, when user clicks the list item of dropdownlist control to select it. A good way of using the InitialValue property is with the DropDownList server control.

For example

a drop-down list might have a default value that is not an empty value (by default, some text appears in it). An example of a drop-down list with the RequiredFieldValidator that uses the without InitialValue property is illustrated in Below code.

ASPX PAGE:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:dropdownlist id="dropDowncolor" runat="server">

    <asp:ListItem Text="Select Color" Value="none" />

        <asp:ListItem Text="Red" Value="Red" />   

        <asp:ListItem Text="Blue" Value="Blue" />   

        <asp:ListItem Text="Green" Value="Green" /> 

</asp:dropdownlist>

       <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"ControlToValidate="dropDowncolor" ErrorMessage="Please select color"></asp:RequiredFieldValidator>

<p>

<asp:button id="btnSubmit" runat="server" text="Submit" onclick="SubmitData" />

</p>

     </div>

    </form>

</body>

</html>

Now run the application

ddl1.gif
 

DropDownList1

Now using InitialValue property in the RequiredFieldValidator control.

<div>

    <asp:dropdownlist id="dropDowncolor" runat="server">

    <asp:ListItem Text="Select color" Value="0" />

    <asp:ListItem Text="red" Value="18" />

    <asp:ListItem Text="blue" Value="19" />

    <asp:ListItem Text="pink" Value="20" />

    <asp:ListItem Text= "green" Value=">20" />

</asp:dropdownlist>

<asp:requiredfieldvalidator id="reqcolor" runat="server" errormessage="Please select color"forecolor="Red" controltovalidate="dropDowncolor" initialvalue="0" />

<p>

   <asp:button id="btnSubmit" runat="server" text="Submit" onclick="SubmitData" />

</p>

 </div>

 

Now run the application and click on the Button control.

ddl2.gif
 

DropDownList2

Now select item from the DropDownList.

ddl3.gif
 

DropDownlist3

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.