One of the members in the forum (forums.asp.net) 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:

ASPX:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>        

         <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>

        </asp:ListBox>

    </div>

    </form>

</body>

</html>

 

CODE BEHIND:

protected void Page_Load(object sender, EventArgs e) {

        if (!Page.IsPostBack)

        {

            ListBox1.ClearSelection();

        }

    }

 

    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;

        }

        else{

            lastSelectedIndex = ListBox1.SelectedIndex;

        }

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

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

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

                    count++;

                    ViewState["CountLimit"] = count;

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

                }

                else {

                    count++;

                    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: ,