Skip to content

Mutually Exclusive Checkboxes inside a GridView

The easiest way to implement mutually exclusive CheckBoxes is to use the MutuallyExclusiveCheckbox control from the AjaxControlToolKit. You assign the control to every Checkbox and give each control a common key.

<asp:CheckBox runat="server" ID="cb1" Text="Cb1" />
<ajx:MutuallyExclusiveCheckboxExtender runat="server" ID="mecCb1" TargetControlID="cb1"   key="mux1" /> 

<asp:CheckBox runat="server" ID="cb2" Text="Cb2" />
<ajx:MutuallyExclusiveCheckboxExtender runat="server" ID="mecCb2" TargetControlID="cb2"   key="mux1" />

It’s the same thing when you are inside a GridView and you want the CheckBoxes on a row be mutually excluded. The only difference is to make every key unique. You can do that, for example, by assigning the key at runtime based on the GridView row.

<asp:CheckBox runat="server" ID="cb1" Text="Cb1" />
<ajx:MutuallyExclusiveCheckboxExtender runat="server" ID="mecCb1" TargetControlID="cb1" /> 

<asp:CheckBox runat="server" ID="cb2" Text="Cb2" />
<ajx:MutuallyExclusiveCheckboxExtender runat="server" ID="mecCb2" TargetControlID="cb2" />

Note how the key attribute is omitted. It will be set inside the RowDataBound event handler.

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        AjaxControlToolkit.MutuallyExclusiveCheckBoxExtender mux = row.FindControl("mecCB1") as AjaxControlToolkit.MutuallyExclusiveCheckBoxExtender;
        if (mux != null)
            mux.Key = "cbKey" + row.RowIndex;
        ... same for other CheckBoxes ...
    }
}

One Comment

  1. Somnath

    Thanks a lot….

Leave a Reply

Your email address will not be published. Required fields are marked *

*