form validation on dropdownlist

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
 
M

marc.derider

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top