Non-Selectable ListItems
Example 3: Using A Custom Validator

Select a vacation

This page demonstrates how to use a CustomValidator control to create "non-selectable" ListItem controls within a DropDownList or similar ASP.NET control that uses ListItems as data items.

Page Code

            <asp:DropDownList runat="server" ID="ddlVacation" AutoPostBack="true" OnSelectedIndexChanged="ddlVacation_postBack">
                <asp:ListItem Text="-- Sunny Island -- " Value="" />
                <asp:ListItem Value="Aruba" />
                <asp:ListItem Value="Hawaii" />
                <asp:ListItem Value="Bermuda" />
                <asp:ListItem Text="-- Snowy Getaway --" Value="" />
                <asp:ListItem Value="Vail, CO" />
                <asp:ListItem Value="Nome, AK" />
                <asp:ListItem Value="Greenland" />
                <asp:ListItem Value="The North Pole" />
                <asp:ListItem Value="Antartica" />
                <asp:ListItem Text="-- Big Adventure --" Value="" />   
                <asp:ListItem Value="Mt. Everest" />
                <asp:ListItem Value="The Amazon River" />
            </asp:DropDownList>
            <asp:Label runat="server" ID="lblMessage" Text="Select a vacation" />
            <asp:CustomValidator runat="server" ID="cvVacation" OnServerValidate="cvVacation_serverValidate" ForeColor="Red" Font-Bold="true" ErrorMessage="Sorry, that's not an option. Please try again." Display="Dynamic" />
        

Code Behind

            Sub ddlVacation_postBack(ByVal Sender As Object, ByVal E As EventArgs)
                Page.Validate()
                If Page.IsValid Then
                    lblMessage.Text = "I would love to go to <strong>" & ddlVacation.SelectedValue & "</strong>!"
                End If
            End Sub

            Sub cvVacation_serverValidate(ByVal Sender As Object, ByVal E As ServerValidateEventArgs)
                If ddlVacation.SelectedValue = String.Empty Then
                    E.IsValid = False
                    lblMessage.Text = ""
                End If
            End Sub