Mutually exclusive checkbox in GridView using Javascript
I response to one of my blog post entry I received few queries regarding mutually exclusive checkbox within GirdView, meaning if there are two checkboxes in a row only one can be selected at a time. If checkbox1 is selected and you select checkbox2 then checkbox1 should be deselected. Following javascript and html can be used.
<script type="text/javascript">
function checkMutuallyExclusive(target)
{
document.getElementById(target).checked = false;
}
</script>
.
.
.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="cbStatus1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbStatus1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
AlternatingItemTemplate>
<asp:CheckBox ID="cbStatus2" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbStatus2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
----------------------------------.vb file if VB.Net is the language ------------------------------------
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
DirectCast(e.Row.FindControl("cbStatus1"), CheckBox).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" & DirectCast(e.Row.FindControl("cbStatus2"), CheckBox).ClientID & "')")
DirectCast(e.Row.FindControl("cbStatus2"), CheckBox).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" & DirectCast(e.Row.FindControl("cbStatus1"), CheckBox).ClientID & "')")
End If
End Sub
----------------------------------.cs file if C#.Net is the language ------------------------------------
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow)) {
((CheckBox)e.Row.FindControl("cbStatus1")).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" + ((CheckBox)e.Row.FindControl("cbStatus2")).ClientID + "')");
((CheckBox)e.Row.FindControl("cbStatus2")).Attributes.Add("onclick", "javascript:checkMutuallyExclusive('" + ((CheckBox)e.Row.FindControl("cbStatus1")).ClientID + "')");
}
}