Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a nullable bool to a checkbox?

I am displaying information as a checkbox with ThreeState enabled, and want to use a nullable boolean in simplest way possible.

Currently I am using a nested ternary expression; but is there a clearer way?

bool? foo = null;
checkBox1.CheckState = foo.HasValue ?
    (foo == true ? CheckState.Checked : CheckState.Unchecked) :
    CheckState.Indeterminate;

* Note that the checkbox and form is read-only.

like image 387
JYelton Avatar asked Apr 27 '12 20:04

JYelton


2 Answers

That's how I would do it.

I would add an extension method to clean it up a bit.

    public static CheckState ToCheckboxState(this bool booleanValue)
    {
        return booleanValue.ToCheckboxState();
    }

    public static CheckState ToCheckboxState(this bool? booleanValue)
    {
        return booleanValue.HasValue ?
               (booleanValue == true ? CheckState.Checked : CheckState.Unchecked) :
               CheckState.Indeterminate;
    }
like image 199
Nathan Koop Avatar answered Nov 06 '22 09:11

Nathan Koop


More clear is an arguable statement. For example I could say that this is more clear.

if(foo.HasValue)
{
    if(foo == true) 
       checkBox1.CheckState = CheckState.Checked;
    else
       checkBox1.CheckState = CheckState.Unchecked;
}
else
    checkBox1.CheckState  = CheckState.Indeterminate;

Another option would be to create a method just for this:

checkBox1.CheckState = GetCheckState(foo);

public CheckState GetCheckState(bool? foo)
{
    if(foo.HasValue)
    {
        if(foo == true) 
           return CheckState.Checked;
        else
           return CheckState.Unchecked;
    }
    else
        return CheckState.Indeterminate

}

However I like your code.

like image 28
Steve Avatar answered Nov 06 '22 11:11

Steve