Introduction:
In this article I will explain with an example, how to implement mutually exclusive CheckBoxList (CheckBoxes) inside GridView in ASP.Net using JavaScript and jQuery.
Mutually exclusive CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.
CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.
HTML aspx code:
In this article I will explain with an example, how to implement mutually exclusive CheckBoxList (CheckBoxes) inside GridView in ASP.Net using JavaScript and jQuery.
Mutually exclusive CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.
CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.
HTML aspx code:
<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>
C# code:
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", "John Brown", "United States");
dt.Rows.Add(2, "F", "Asma Qureshi", "Pakistan");
dt.Rows.Add(3, "M", "Thomas Methieo ", "France");
dt.Rows.Add(4, "M", "Robert Farnen", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
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;
}
}