How can I set a databound checkbox in a GridView control?

Issue

How can I set a databound checkbox in a GridView control? I have a checkbox in my GridView but its check status does not stay.

Solution

There are two ways to add a checkbox to a GridView control.

Method 1: Using CheckBoxField

WorkflowPage will automatically perform the binding. The limitation is that the GridView column can only have the checkbox.

<asp:CheckBoxField DataField="MyCheckBox" HeaderText="Header of My Checkbox" />

Method 2: Using TemplateField

You can have a checkbox control and other controls within the same GridView. However, there is no direct databinding to a checkbox for the GridView dataRow. You need to convert the data value to checkbox Boolean check state.

To manually databind a checkbox:

  1. Display the checkbox status in ASPX.

  2. In aspx.cs, capture the checkbox status in onRowUpdating.

ASPX

Get the checkbox data and convert it to Boolean value for the checkbox status.

It converts the string value of MyCheckBox in Boolean true/false.

In ItemTemplate, set Enabled=false:

<asp:TemplateField HeaderText=" Header of My Checkbox">
 <EditItemTemplate>
 <asp:CheckBox ID="MyCheckBox" runat="server"
Checked='<%# Eval("MyCheckBox").ToString() == "True" ? true:false %>' />
 </EditItemTemplate>
 <ItemTemplate>
  <asp:CheckBox ID="MyCheckBox" runat="server" Enabled="false"
Checked='<%# Eval("MyCheckBox ").ToString() == "True" ? true:false %>' />
 </ItemTemplate>
</asp:TemplateField>

ASP.CS

Capture the checkbox status at RowUpdating. Set its value in the GridView data, which will be handled by WorkflowGen.

protected void MyGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CheckBox chkbox =
 (CheckBox)MyGridView.Rows[e.RowIndex].FindControl("MyCheckBox");
 if (chkbox.Checked)
 e.NewValues["MyCheckBox "] = "True";
 else
 e.NewValues["MyCheckBox"] = "False";
}