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