Sunday, February 28, 2010

CheckBox Class Bound to Non-Booleans

Well, it’s been awhile since I’ve posted. I have no excuse, other than I’ve been super-busy, but aren’t we all? So … lousy excuse. One of my kids, who calls frequently, always starts out the conversation with “So, what are you doing?” and I always reply “Working”. That invariably gets a response from him of  “How can an un-employed person always be working?!?” Well, just because I’m not getting paid, doesn’t mean that I’m not busy working on the next latest-and-greatest idea to save humanity … or at least make life easier. ;0)

Anyway, that said, I’m going to post a pretty quick-and-dirty class here, but it addresses an issue I see frequently asked on the forums. As we all know, a CheckBox is typically bound to a boolean value. I mean, it’s either checked or it’s not … true or false. But, sometimes developers  have to deal with legacy data from legacy databases, or maybe just poorly designed databases, where something other than a boolean (or bit in many databases) is used to represent true/false … character strings such as “T”/”F” or “Y”/”N”.

The key point to making this work, is to handle the Format and Parse events of the Binding. This class can be extended to be able to used with other strings, such as “T”/”F”, but I’ll leave that as an exercise for the reader:

public class BBCheckBoxString : System.Windows.Forms.CheckBox
{
protected Binding oBinding = null;

public virtual void DataBind(System.Data.DataTable Data, string Column)
{
this.Checked = false;
this.oBinding = new Binding("Checked", Data, Column);

this.oBinding.Format += new ConvertEventHandler(this.FormatHandler);
this.oBinding.Parse += new ConvertEventHandler(this.ParseHandler);

this.DataBindings.Add(this.oBinding);
}
protected virtual void FormatHandler(object sender, ConvertEventArgs e)
{
if (e.Value.ToString() == "Y")
e.Value = true;
else
e.Value = false;
}
protected virtual void ParseHandler(object sender, ConvertEventArgs e)
{
if ((bool)e.Value == true)
e.Value = "Y";
else
e.Value = "N";
}
}

Pretty easy, right? The Format event takes the value of the column in your DataTable (“Y”/”N”) and converts it to true/false to be displayed as a checkmark (or empty box). The Parse handler does the opposite. It takes the value of the Checked property (true/false) and converts it to “Y”/”N” to be placed back in the data column.