form validation on dropdownlist

  • Thread starter Thread starter dopey
  • Start date Start date
D

dopey

I have a dropdownlist on my asp form.
the first item of the list is text like "please select",
the other items are populated by a database.

Can i use the RequiredFieldValidator control with my
dropdownlist, so that it does not accept "please select"
as a valid selection and will display a messge to the
user.

thank you very much
 
yes you can. If you simply set the Value of the ListItem to "" then it
will have an empty value. If you do not set a value then it will be
given the value of the text.

See below code snippet which does what you need it to do.

<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Value="">Please select one</asp:ListItem>
<asp:ListItem Value="1">Cats</asp:ListItem>
<asp:ListItem Value="2">Dogs</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Please select a pet."
ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
 
Back
Top