I want to display an array of checkboxes in a gridview.
It should look like this:

But, there is a trick – my database query returns booleans, but the only thing I can bind to the “checked” property of the asp:checkbox control is a string. Too bad. I’ll include some of the work arounds I attempted – I thought they were interesting, but nothing worked.
(OOPS - word press is deleting my code ... sorry)
<asp:Label ID="lblTest" runat="server" Text='' />
<asp:CheckBox ID="test" runat="server" Checked='' />
<asp:CheckBox ID="test" runat="server" Checked= />
The checkbox above returned “InvalidCastException”. Take my word for it, I tried many variations on the above.
So how did I eventually get the display to work?
I think there are two possible ways.
I did not attempt a server side handling of the row-data-bound event to find the checkbox control and set it to the correct value, although I think that would work.
Instead, I made a simple user control called a StringCheckBox, and set it with the “1″ or “0″ that my bind syntax was producing, and that worked well.
REVISION – when a simple checkbox is printed, it never prints as checked. I don’t know why. I changed the control so that it displays two images instead of the checkbox.
Here is the (revised) server side of the control in its entirety:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace TBRSurvey.UTReports
{
public partial class ctlStringCheckBox : System.Web.UI.UserControl
{
private string m_checked ="";
public string ctl_checked
{
get { return m_checked; }
set { m_checked = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
CheckBox1.Checked = false;
// images from http://openacs.org/doc/acs-subsite/images.html
imgCheckBox.ImageUrl = "~/images/checkbox.gif";
if (m_checked == "1")
{
CheckBox1.Checked = true;
imgCheckBox.ImageUrl = "~/images/checkboxchecked.gif";
}
if (m_checked.ToLower() == "true")
{
CheckBox1.Checked = true;
imgCheckBox.ImageUrl = "~/images/checkbox.gif";
}
}
}
}