Original Source

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 usingRequiredFieldValidator, however sometimes we need to validate aDropDownList/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 useRequiredFieldValidator however with one extra property.

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 !