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.

CODE BEHIND:

protectedvoid 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.