Tuesday, 23 June 2015

Implement Mutually Exclusive CheckBoxList (CheckBoxes) inside GridView in ASP.Net

Mutually exclusive CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.

 HTML Markup
The following HTML Markup consists of a GridView with two BoundField columns and a TemplateField column containing an ASP.Net CheckBoxList control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
        <asp:TemplateField HeaderText="Gender" ItemStyle-Width="150">
            <ItemTemplate>
                <asp:CheckBoxList ID = "chkGender" runat="server" RepeatDirection = "Horizontal">
                    <asp:ListItem Text="Male" Value="M" />
                    <asp:ListItem Text="Female" Value="F" />
                </asp:CheckBoxList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>


protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Id"), new DataColumn("Gender"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "M", "Sujoy Santra", "India");
        dt.Rows.Add(2, "M", "Sumit Kumar Sen", "Brazil");
        dt.Rows.Add(3, "F", "Soumi Santra", "India");
        dt.Rows.Add(4, "M", "Mithun Patra", "Canada");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}







 Populating the Selected Value of CheckBoxList in GridView
Inside the OnRowDataBound event handler of GridView, first the value of Gender is determined from the DataItem object of the GridView.
Finally the CheckBoxList is referenced using the FindControl method and its selected value is set.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string gender = (e.Row.DataItem as DataRowView)["Gender"].ToString();
        CheckBoxList chkGender = (e.Row.FindControl("chkGender") as CheckBoxList);
        chkGender.Items.FindByValue(gender).Selected = true;
    }
}

 Implement Mutually Exclusive CheckBoxList (CheckBoxes) inside GridView
Inside the jQuery document ready event handler, a click event handler is assigned to each CheckBox of all the CheckBoxLists present inside the GridView.
When a CheckBox is clicked in a CheckBoxList, all the CheckBoxes except the current are unchecked.
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=chkGender] input").click(function () {
            $(this).closest("table").find("input").not(this).removeAttr("checked");
        });
    });
</script>