DropDownList example: Validate DropDownList control in asp.net


Validate a Drop-Down List on a Form

The easiest way to make ensure that a user picks a value from a dropdown list is to add a value to the top of the list that isn't really a valid choice, but a prompt instead. Something like "select one" should do.
The validatedropdown.aspx page code Look like this

<%@ Page Language="C#" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<script runat="server"> 
    protected void btnsubmit_Click(object sender, System.EventArgs e)
    {
        lblmsg.Text = "You selected: " +
            ddvalidate.SelectedItem.Text.ToString(); 
    } 
</script> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title>DropDownList example: Check how to validate DropDownList control in asp.net</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
        <asp:Label ID="lblmsg" runat="server" Font-Size="Large" ForeColor="Crimson"></asp:Label> 
        <br /> 
        <asp:DropDownList ID="ddvalidate" runat="server"> 
            <asp:ListItem Selected="True">Select One</asp:ListItem> 
            <asp:ListItem>.NET Interview questions</asp:ListItem> 
            <asp:ListItem>asp.net interview questions</asp:ListItem> 
            <asp:ListItem>Asp.Net Calendar Example</asp:ListItem> 
            <asp:ListItem>Asp.Net DataGrid Example</asp:ListItem> 
            <asp:ListItem>Asp.Net DataList Example</asp:ListItem> 
            <asp:ListItem>Asp.Net Gridview Example</asp:ListItem> 
        </asp:DropDownList> 
        <asp:RequiredFieldValidator 
             ID="RequiredFieldValidator1" 
             runat="server" 
             ControlToValidate="ddvalidate" 
             InitialValue="Select One" 
             ErrorMessage="Select One!" 
             > 
        </asp:RequiredFieldValidator> 
        <br /> 
        <asp:Button ID="btnsubmit" runat="server" Text="Check Validate DropDownList" OnClick="btnsubmit_Click" /> 
    </div> 
    </form> 
</body> 
</html>  

Tags: ,

Join Us!