Tuesday, July 7, 2009

Changing the background color of a checkbox at runtime

I wanted to show 3 values in a checkbox ("full", "partial", and "empty") by changing background color of the selected checkbox when state is "partial"

I thought we could simply set the background color property, but that had no effect for me at runtime. It took a while to find how to programatically change background color of a checkbox on a VB web form, finally this post and this post got me close enough.

How to change the color at runtime:

(1) Add CSS style declarations to your form's design view (.aspx page), for example:

.full {
background-color: #fff;
}
.partial {
background-color: #ccc;


(2) in the form load method add some code like this:

curControl = CType(Page.FindControl(sID), CheckBox)

if (ispartial) then
curControl.Checked = True
curControl.CssClass = "partial"
else if (isfull) then
curControl.Checked = True
curControl.CssClass = "full"
etc.

No comments: