How to validate a DropdownList/ListBox?

Itfunda
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 12185 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we are going to learn how to validate a DropdownList/ListBox.

Introduction

Normally we validate a TextBox to make it mandatory by using RequiredFieldValidator, however sometimes we need to validate a DropDownList/ListBox so that user doesn’t select the default selected item from it. To validate a DropDownList/ListBox as a mandatory field so that user has to select an item other than the default selected item we can still use RequiredFieldValidator however with one extra property.

To get hundreds of real time .NET How to solution, click here.

Let’s see this with example. First create a .aspx page and paste below code.

ASPX PAGE:

Select age:

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

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

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

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

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

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

</asp:dropdownlist>

<asp:requiredfieldvalidator id="reqAge" runat="server" errormessage="Please select age" forecolor="Red" controltovalidate="dropDownAge" initialvalue="0" />

<p>

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

</p>

CODE BEHIND:

protected void SubmitData(object sender, EventArgs e)

{

 

}

In the above code snippet, the first item of the DropDownList is “Select Age” with value as “0”; we want the user to select any age apart from “0”. To do that we can specify the RequiredFieldValidator’s “InitialValue” as “0”, this will cause the RequiredFieldValidator fail unless user select any age other than “0” from the DropDownList.

Now when we run the page with above code snippets, its output should appear something like below image and when we click the Submit button without selecting any age apart from “0” that is “Select Age” item, we shall get error like below

Note: Similarly we can perform the validation for ListBox control as well.

Conclusion:

Hope this was useful article, keep reading, learning and sharing !

Page copy protected against web site content infringement by Copyscape

About the Author

Itfunda
Full Name: IT Funda
Member Level: Starter
Member Status: Member
Member Since: 5/21/2011 3:32:40 AM
Country: India
Thanks Regards
http://www.itfunda.com/
Get .NET How to | jQuery How to.

Login to vote for this post.

Comments or Responses

Posted by: Akiii on: 5/29/2011 | Points: 25
nice one...

Regards
Akiii

Login to post response

Comment using Facebook(Author doesn't get notification)