Main Contents

Binding A String to a Checkbox

Schotime @ April 2, 2008

.NET

In a recent project I was attempting to list data from a configuration settings database table. The values were boolean but stored as a ‘Y’ or a ‘N’ so that only one set of SQL’s was needed to be written, as the product supports both Oracle and SQL Server.

When I first put the GridView together, I was surprised to find that there was no Value property for the asp:checkbox nor could you bind any other column in a database but a ‘bit’ column to it.

The only solution I could come up with was to create a custom Checkbox and implement the feature. Below is the code for the custom Checkbox.

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace ServerControls
{
    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    [ToolboxData("<{0}:CheckBoxValue runat=server></{0}:CheckBoxValue>")]
    public class CheckBoxValue : CheckBox
    {
        private string _value;
        private string _unCheckedValue;
        private string _checkedValue;
 
        public string Value
        {
            get { return _value; }
            set
            {
                _value = value;
                if (value != null && this.CheckedValue != null && this.UnCheckedValue != null)
                    base.Checked = value == this.CheckedValue;
            }
        }
 
        public string CheckedValue
        {
            get { return _checkedValue; }
            set { _checkedValue = value; }
        }
 
        public string UnCheckedValue
        {
            get { return _unCheckedValue; }
            set { _unCheckedValue = value; }
        }
 
        public override bool Checked
        {
            get { return base.Checked; }
            set
            {
                base.Checked = value;
                if (this.Value != null && this.CheckedValue != null && this.UnCheckedValue != null)
                    this.Value = value ? this.CheckedValue : this.UnCheckedValue;
            }
        }
 
        protected override void OnInit(EventArgs e)
        {
            Page.RegisterRequiresControlState(this);
            base.OnInit(e);
        }
 
        protected override object SaveControlState()
        {
            object[] state = new object[2];
            state[0] = base.SaveControlState();
            state[1] = this.Value;
            return state;
        }
 
        protected override void LoadControlState(object state)
        {
            object[] stateTmp = (object[])state;
            base.LoadControlState(stateTmp[0]);
            this.Value = (string)stateTmp[1];
        }
    }
}

The magic in the custom checkbox occurs in the Value property and the overridden Checked property.

When the value property is set, if it is the same as the ‘CheckedValue’ property then we set the base.Checked value to true else false. The same principles apply to the overridden Checked property. When the property is set we set the Value property to the ‘CheckedValue’ property if Checked equals true else we set it to the ‘UnCheckedValue’.

Once compiled we can then use this inside our GridView template and bind a varchar column from a database to it. Here is the syntax.

<Custom:CheckBoxValue
        ID="cbv1"
        runat="server"
        CheckedValue="Y"
        UnCheckedValue="N"
        Value='<%# Bind("valueyn") %>' />

So when the GridView databinds and evaluates the ‘valueyn’ column; if the value is ‘Y’ then the checkbox will be checked and if the value is ‘N’ then the checkbox will be unchecked. Then if I choose to edit a line with the checkbox and change its value, the value stored in the database will match the value of the checkbox. eg. if the checkbox is checked, ‘Y’ will be entered into the database and if it is left unchecked then ‘N’ will be entered.

This seems to work extremely well for my project and suits my needs. It will even work if the ‘valueyn’ column is an Int, as long as you modify the ‘CheckedValue’ and ‘UnCheckedValue’ to something that can be implicitly converted to an Int.

Hope this helps. If you find any issues or have other ideas please don’t hesitate to leave a comment.


book mark Binding A String to a Checkbox in del.icio.us submit Binding A String to a Checkbox to digg.com


6 Comments

  1. Binding A String to a Checkbox - Adam Schroder April 2, 2008 @ 6:13 pm

    [...] Click here to keep reading and get the code… Posted: Apr 02 2008, 05:13 PM by schotime | with no comments Filed under: ASP.NET, C#, Custom Controls [...]

  2. Hiho September 19, 2008 @ 6:00 pm

    Great !

    I used it in a detailsview to bind “1″ & “0″ values with the checkbox. Now my DetailsView supports 2 way databinding with the SqlDataSource. It seems that a classic CheckBox in a TemplateField can’t bind itself because it hasn’t the “[Bindable(true)]“.

  3. Dave February 26, 2009 @ 2:14 am

    There is a bug in this code. In the Checked method the if statement should be as follows

    if (this.CheckedValue != null && this.UnCheckedValue != null)

    notice there shouldn’t be the this.CheckedValue != null, but that should be in the set of the Value property

  4. Schotime February 26, 2009 @ 8:34 am

    What errors do you get? Works fine in production for me.

  5. Tony April 15, 2010 @ 11:26 pm

    This is great!! I like how how it was done, but I get a weird compiler error. I must be overlooking something but I get the following error:

    Compiler Error Message: CS0433: The type ‘ServerControls.CheckBoxValue’ exists in both ‘c:\Users\tony\AppData\Local\Temp\Temporary ASP.NET Files\root7df7580\d2b1a73c\assembly\dl3\e59233f7\ebe00f03_9fdcca01\MyAdmin.DLL’ and ‘c:\Users\tony\AppData\Local\Temp\Temporary ASP.NET Files\root7df7580\d2b1a73c\App_Code.yrmbofkl.dll’

    Any help you can give on this specific error?

    Thanks!!!

  6. DANIELLE CARVER June 1, 2010 @ 11:16 am

    I have been looking around schotime.net and really am impressed by the exceptional content here. I work the nightshift at my job and it is boring. I have been coming right here for the past couple nights and reading. I simply wanted to let you know that I have been enjoying what I have seen and I look ahead to reading more.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Feed
26,580 spam comments
blocked by
Akismet