Language

Creating Mutually Exclusive Checkboxes (VB)

By Christian Wenz|

Download Code or Download PDF

When only one of a set of options may be selected, radio buttons are usually used. There is a drawback, though: Once one radio button in a group is selected, it is not possible to uncheck all radio buttons. Check boxes can be unchecked at any time, however are not mutually exclusive. This tutorial provides the best of both approaches: check boxes that are mutually exclusive.

Overview

When only one of a set of options may be selected, radio buttons are usually used. There is a drawback, though: Once one radio button in a group is selected, it is not possible to uncheck all radio buttons. Check boxes can be unchecked at any time, however are not mutually exclusive. This tutorial provides the best of both approaches: check boxes that are mutually exclusive.

Steps

The ASP.NET AJAX Control Toolkit contains the MutuallyExclusiveCheckBox extender. This enables programmers to assign any checkbox to a group name (Key attribute). From all check boxes within the same group, only one may be selected at one time.

Let's start with putting two check boxes on a new ASP.NET page. There can be more, but two of them suffice to demonstrate the principle:

<asp:CheckBox ID="cbYes" runat="server" />Yes <asp:CheckBox ID="cbNo" runat="server" />No

For both checkboxes, a MutuallyExclusiveCheckBoxExtender control must be put on the page. Both Key attributes need to have the same value, just as the value attributes of HTML radio button elements must be identical to denote the group they belong to. The TargetControlID property of the extender points to the ID of the check box.

<ajaxToolkit:MutuallyExclusiveCheckBoxExtender ID="mecbe1" runat="server" TargetControlID="cbYes" Key="YesNo" /> <ajaxToolkit:MutuallyExclusiveCheckBoxExtender ID="mecbe2" runat="server" TargetControlID="cbNo" Key="YesNo" />

Finally, include the ASP.NET AJAX ScriptManager which is required by all elements of the ASP.NET AJAX Control Toolkit:

<asp:ScriptManager ID="asm" runat="server" />

Save and run the page: You can check and uncheck both check boxes, however at no time can both check boxes be checked.

Only one checkbox can be checked at a time (Click to view full-size image)

This article was originally created on June 2, 2008

Author Information

Christian Wenz

Christian Wenz – Christian Wenz is an author, trainer, and consultant. His main focus of working and writing is on web technologies and security. Christian has written or co-written over 100 books for various publishers. He works with both open source and closed source web technologies. This leads to the unusual situation that he has both been awarded a Microsoft MVP for ASP/ASP.NET and is listed in Zend's Who is Who of PHP. He is also listed in Mozilla's credits (about:credits) and is considered an expert in browser-agnostic JavaScript.