Thursday, December 13, 2012

ASP.NET Validation Controls: Validating DropDown List Selection

Some times when user submitting the web form we need to make sure that the dropdown list is selected other than it's default values.

In the example "Select Below" is the default text and the values is "0" in the dropdown list. Validation fires if the selected value is "0" that means when the selected text is "Select below".

Let's load some values to the dropdown list.

private void LoadDropDown()
  DropDownList2.Items.Insert(0,new ListItem("Select Below","0"));
  DropDownList2.Items.Insert(1,new ListItem("Item1","1"));
  DropDownList2.Items.Insert(2, new ListItem("Item2", "2"));
  DropDownList2.Items.Insert(3, new ListItem("Item3", "3"));
  DropDownList2.Items.Insert(4, new ListItem("Item4", "4"));

Below is the HTML code.

<asp:DropDownList ID="DropDownList2" runat="server">

&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList2" ForeColor="#CC0000" InitialValue="0">*</asp:RequiredFieldValidator>
<br />
<tr style="font-weight: bold">
<asp:Button ID="Button2" runat="server" Text="Submit" />

We have used the RequiredFieldValidator Control. Note the Initial values property, it's set to "0".

No comments:
Write comments
Recommended Posts × +