How to Validate ListBox in

ListBox Example: How to Validate ListBox

In this example 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.

C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;

namespace asptutorial
    public partial class blankpage : System.Web.UI.Page

      protected void Page_Load(object sender, EventArgs e)
            Label1.Visible = false;
            Button1.Text = "Send";

            RequiredFieldValidator1.ErrorMessage = "Please select an Item";
            RequiredFieldValidator1.ForeColor = System.Drawing.Color.Red;
            RequiredFieldValidator1.ControlToValidate = ListBox1.ClientID;



        protected void Button1_Click(object sender, EventArgs e)
            Label1.Visible = true;
            Label1.Text = "You selected : " + ListBox1.SelectedItem.Text.ToString()+""; 



<%@ Page Language="C#" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">  
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e) {  
        Label1.Text = "You selected : <b>" + ListBox1.SelectedItem.Text.ToString()+"</b>";  
<html xmlns="">
<head runat="server">
    <title> Button Control </title>
    <form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server"  />  
        <br />  
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Single">  
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ListBox1" ErrorMessage="Please select an Item" ForeColor="Red">  
        <br />
        <asp:Button ID="Button1" runat="server" Text="Send" OnClick="Button1_Click" />  
How to Validate ListBox in
How to Validate ListBox in

Share this article on