How to Validate ListBox in asp.net

ListBox Example: How to Validate ListBox

In this example I present how we can validate a ListBox Control. Here I use RequiredFieldValidator Control to validate ListBox.

ListBox RequiredFieldValidator
Create a Web Form name ListBoxValidation.aspx. We can use RequiredFieldValidator Control for ListBox Control's Validation check. Here I show that a visitor must be select one Item when he submits the page. If he not selects any item then the RequiredFieldValidator Control shows an error message. The source code of ListBoxValidation.aspx is below.

<%@ 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 Button1_Click(object sender, System.EventArgs e) {
        Label1.Text = "You selected : " +
            ListBox1.SelectedItem.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ListBox Example: How to Validate ListBox Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="Crimson" />
        <br /><br />
        <asp:Label ID="Label2" runat="server" Text="What you want to see?" />
        <br />
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Single">
            <asp:ListItem>RadioButton Example</asp:ListItem>
            <asp:ListItem>RadioButtonList Example</asp:ListItem>
            <asp:ListItem>CheckBox Example</asp:ListItem>
            <asp:ListItem>CheckBoxList Example</asp:ListItem>
            <asp:ListItem>PlaceHolder Example</asp:ListItem>
            <asp:ListItem>AdRotator Example</asp:ListItem>
            <asp:ListItem>Xml Example</asp:ListItem>
            <asp:ListItem>DropDownList Example</asp:ListItem>
        </asp:ListBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ListBox1" ErrorMessage="Please select an Item">
        </asp:RequiredFieldValidator>
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Check ListBox Validation" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>








Related asp.net example