We have seen ASP.Net RadioButtons and RadioButtonList control the main aim of these controls is Mutual Exclusion that is one can select only one out of N items if another item is selected the previous one gets unchecked. The only issue is that once you check one in a group of RadioButtons you cannot uncheck them that is you cannot return to the state when all were unchecked. Hence in such case you need to provide a Clear Selection Button which will clear the checked items.
Another solution is to make a ASP.Net CheckBox or CheckBoxList mutually exclusive using JavaScript thus we get the following two features
1. User can select only one item like ASP.Net RadioButton Group
2. User can also uncheck his selection which he is not able to do in case of RadioButton group
Let’s start with a JavaScript function shown below
<script type = "text/javascript">
function MutExChkList(chk)
{
var chkList = chk.parentNode.parentNode.parentNode;
var chks = chkList.getElementsByTagName("input");
for(var i=0;i<chks.length;i++)
{
if(chks[i] != chk && chk.checked)
{
chks[i].checked=false;
}
}
}
</script>
The above function gets called when a CheckBox in the ASP.Net CheckBoxList Control is clicked it simply then loops and unchecks all the other CheckBoxes Thus making it mutually exclusive.
To call the function you have to add a JavaScript onclick event handler to the CheckBoxList as shown below
Either you simply add onclick event in the aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text = "1" Value = "1" onclick = "MutExChkList(this);">
</asp:ListItem>
<asp:ListItem Text = "2" Value = "2" onclick = "MutExChkList(this);">
</asp:ListItem>
<asp:ListItem Text = "3" Value = "3" onclick = "MutExChkList(this);">
</asp:ListItem>
<asp:ListItem Text = "4" Value = "4" onclick = "MutExChkList(this);">
</asp:ListItem>
<asp:ListItem Text = "5" Value = "5" onclick = "MutExChkList(this);">
</asp:ListItem>
</asp:CheckBoxList>
Doing the above will raise warnings in the Visual Studio which can be ignored. If you don’t want warnings do the same in the code behind
C#
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
CheckBoxList1.Items[i].Attributes.Add("onclick", "MutExChkList(this)");
}
VB.Net
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
CheckBoxList1.Items(i).Attributes.Add("onclick", "MutExChkList(this)")
Next
Try it.
This completes the article. Hope you liked it
You can download the code sample using the link below
MutuallyExclusiveCheckBox.zip (3.41 kb)