Geeks With Blogs


Microsoft MVP


Moderator at CodeASP.NET

Quiz Master

free counters
Free counters
Added on January 19,2012

Follow Me @vmsdurano

A bit About Me

The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.

Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

One of the members in the forum ( is asking how to limit the number of selected items in the ListBox and so contributors (including me) gave the OP (Original Poster) different ideas on how to validate it. Some of them provided solution using pure JavaScripts and a mixture of code behind and JavaScript. However the OP doesn’t want to use JavaScript validation for some reason, so I decided to post the solution that I have provided on that thread as a reference to others.

Here it is:


<html xmlns="">

<head runat="server">




    <form id="form1" runat="server">


         <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="109px" SelectionMode="Multiple" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="141px">

        <asp:ListItem >A</asp:ListItem>

        <asp:ListItem >B</asp:ListItem>

        <asp:ListItem >C</asp:ListItem>

        <asp:ListItem >D</asp:ListItem>

        <asp:ListItem >E</asp:ListItem>

        <asp:ListItem >F</asp:ListItem>








protected void Page_Load(object sender, EventArgs e) {

        if (!Page.IsPostBack)






    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)


        int count = 0;

        int limit = 0;

        int lastSelectedIndex = 0;

        if(ViewState["lastSelectedIndex"] != null){

            lastSelectedIndex = int.Parse(ViewState["lastSelectedIndex"].ToString());

            ViewState["lastSelectedIndex"] = lastSelectedIndex;



            lastSelectedIndex = ListBox1.SelectedIndex;


            for (int i = 0; i < ListBox1.Items.Count; i++) {

            if (ListBox1.Items[i].Selected) {

                if (ViewState["CountLimit"] != null) {


                    ViewState["CountLimit"] = count;

                    limit = (int)ViewState["CountLimit"];


                else {


                    ViewState["CountLimit"] = count;


                if (limit > 3) // Selected Item Limit is up to 3


                    Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowBox", "alert('You are only allowed to Select 3 items!');", true);

                    ListBox1.Items[lastSelectedIndex].Selected = false;





That's it! Hope you will find this example useful!

Technorati Tags: ,

Posted on Tuesday, November 24, 2009 2:52 PM ASP.NET , Tips&Tricks | Back to top

Comments on this post: Limit the Number to be Selected in the ListBox control - (Server Side way)

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: