How to Validate ListBox in asp.net


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;

            ListBox1.Items.Add("Html");
            ListBox1.Items.Add("Css");
            ListBox1.Items.Add("Java");
            ListBox1.Items.Add("Asp.Net");

            
        }

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


    }
}

HTML Code

<%@ 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 : <b>" + ListBox1.SelectedItem.Text.ToString()+"</b>";  
    }  
</script>  
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Button Control </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server"  />  
      
        <br />  
      
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Single">  
            <asp:ListItem>Html  
            <asp:ListItem>Css  
            <asp:ListItem>Java  
            <asp:ListItem>Asp.Net  
        </asp:ListBox>  
        
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ListBox1" ErrorMessage="Please select an Item" ForeColor="Red">  
        </asp:RequiredFieldValidator>  
        
        <br />
        
        <asp:Button ID="Button1" runat="server" Text="Send" OnClick="Button1_Click" />  
        
    </div>
    </form>
</body>
</html>
Output
How to Validate ListBox in asp.net
How to Validate ListBox in asp.net

Share this article on