Home
Manage Your Code
Snippet: Validate required drop down lists. (C#)
Title: Validate required drop down lists. Language: C#
Description: Use a CompareValidator to ensure that the user has made a valid selection from a drop down list. Views: 187
Author: Aaron Crandall Date Added: 8/29/2007
Copy Code  
1-------------------------------------
2Here are the drop down list and validator declarations.
3The example here is a list of products.
4-------------------------------------
5<asp:DropDownList ID="lstProducts" runat="server"                
6                DataTextField="ProductName" 
7                DataValueField="ProductID">
8            </asp:DropDownList>
9<asp:CompareValidator ID="valProducts" runat="server" ControlToValidate="lstProducts" 
10	Operator="NotEqual" ValueToCompare="-1" Display="dynamic" CssClass="NormalRed"
11	Text="*Selection Required" ErrorMessage="You must select a Product"></asp:CompareValidator>
12
13-------------------------------------
14Here is the C# code to bind the list and add a default entry.
15Note that the value of the default entry is -1.
16-------------------------------------
17lstProducts.DataSource = GetProducts();
18lstProducts.DataBind();
19insertDefaultItem(lstProducts);
20
21private void insertDefaultItem(DropDownList ddl)
22{
23	ddl.Items.Insert(0, new ListItem("<Select One>", "-1"));
24}
25