Binding A String to a Checkbox

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.

Advertisements
This entry was posted in .NET and tagged , , . Bookmark the permalink.

7 Responses to Binding A String to a Checkbox

  1. Pingback: Binding A String to a Checkbox - Adam Schroder

  2. Hiho says:

    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 says:

    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 says:

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

  5. Tony says:

    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:UserstonyAppDataLocalTempTemporary ASP.NET Filesroot7df7580d2b1a73cassemblydl3e59233f7ebe00f03_9fdcca01MyAdmin.DLL’ and ‘c:UserstonyAppDataLocalTempTemporary ASP.NET Filesroot7df7580d2b1a73cApp_Code.yrmbofkl.dll’

    Any help you can give on this specific error?

    Thanks!!!

  6. 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.

  7. gu10 27smd says:

    *I was very pleased to find this web-site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s