How to Use CheckBox Selection Limit in ASP.NET

The CheckBox control is a very common control of HTML, unlike radio buttons it can select multiple items on a webpage. The CheckBox control in ASP.NET has many properties and some of them are listed below.

Property

Description

AutoPostBack

Specifies whether the form should be posted immediately after the Checked property has changed or not. The default is false.

CausesValidation

Specifies if a page is validated when a Button control is clicked.

Checked

Specifies whether the check box is checked or not.

InputAttributes

Attribute names and values used for the Input element for the CheckBox control.

LabelAttributes

Attribute names and values used for the Label element for the CheckBox control.

runat

Specifies that the control is a server control.  Must be set to "server".

Text

The text next to the check box.

TextAlign

On which side of the check box the text should appear (right or left).

ValidationGroup

Group of controls for which the Checkbox control causes validation when it posts back to the server.

OnCheckedChanged

The name of the function to be executed when the Checked property has changed.

In this article I will teach you how to limit the number of selected items among all the checkboxes on a webpage. The first step is to create an "ASP.NET Empty Web Application".

ChkBxASP1.jpg

Since we have started with an Empty Web Application we need to add a page now. Go to Project > Add New Item (Ctrl+Shift+A); a screen will pop up; add a web form from it and name it "SelectionLimit.aspx".

ChkBxASP2.jpg

The explorer will have SelectionLimit.aspx open for you with some default code. Add a Check Box List either from a toolbox or write the code. Since we need to limit the number of selections we need to call a function or submit our form every time a selection is made in the check box list. For this we will use the property AutoPostBack; set it to "true" since we need to call a function on every Post Back to trigger an event when the selection changes. To do this go to the properties on the bottom-right corner.

ChkBxASP3.jpg

ChkBxASP4.jpg

As soon as you double-click the SelectedIndexChanged, "SelectionLimit.aspx.cs" will show up where you will write code.

We will have the following two functions there:

protected void Page_Load(object sender, EventArgs e), and
protected void MyCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)

Since we have just added CheckBoxList and not added any items to it, so in the "Page_Load" Function we will add items to the CheckBoxList:

ChkBxASP5.jpg

And in the "MyCheckBoxList_SelectedIndexChanged" function we will do the main coding part:

ChkBxASP6.jpg

That is all. Debug your page, you might have noticed in the "if" condition that I used count > 2 i.e. I'm limiting the selection to two selections only i.e. only two items can be selected.


Similar Articles