Validating DropDownList in ASP.Net 2.0

Validating DropDownList in ASP.Net 2.0
11/23/2007 5:14:00 PM GMT



A few minutes ago, I was asked the question how to validate an ASP.Net 2.0 DropDownList with the Validation Controls. First of all, you need to set up the DropDownList. You do need to add an item through the item collection at the top of the collection so you can have a "-- Please Select --" list item. After that, you can either right click on the Validation Control and insert --Please Select -- into the Initial value field, or you can type it in through the Design view.

.aspx page:

<asp:DropDownList ID="drpProjectLinks" runat="server">
    <asp:ListItem Value="../Assignment1/default.aspx">Assignment 1</asp:ListItem>
    <asp:ListItem Value="../Assignment2/default.aspx">Assignment 2</asp:ListItem>
    <asp:ListItem Value="../Assignment3/foo.aspx">Assignment 3</asp:ListItem>
    <asp:ListItem Value="../Assignment4/">Assignment 4</asp:ListItem>
    <asp:ListItem Value="../Assignment5/">Assignment 5</asp:ListItem>
    <asp:ListItem Value="../Assignment6/webservice.aspx">Assignment 6</asp:ListItem>>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqProjectLinks" runat="server" ControlToValidate="drpProjectLinks" ErrorMessage="Please Select a Link!!!" InitialValue="-- Please Select --" /> <asp:Button ID="btnGetProject" runat="server" Text="Go to Project" OnClick="btnGetProject_Click" />

.aspx.cs behind the code page:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        drpProjectLinks.Items.Insert(0, new ListItem("-- Please Select --", ""));
    }
}
protected void btnGetProject_Click(object sender, EventArgs e) {     Response.Redirect(drpProjectLinks.SelectedValue); }

Don't worry, this was not an easy one to discover; I have spent numorous afternoons researching this, then by accident figured it out!

Site Administrator



Posts On: Validating DropDownList in ASP.Net 2.0

Thanks!
11/30/2007 5:32:39 PM GMT



Thanks for Joe great help!

URL:




Comment On: Validating DropDownList in ASP.Net 2.0

Title:
Chars left:50
 



Your Name:
Chars left:50
 

Comment:
Chars left:
2540
 





Email:
Chars left:100
   

Website:
Chars left:100
(if none, then leave blank)

Please type in the Characters in the yellow box into the Authentication field.
Authentification: SPAM BLOCKER!!!