I am currently storing the true/false status of a checkbox.Checked value in the registry to reset the next time a form is loaded.
When the form is loaded I get the value and set the checkbox like this.
string value = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\CompanyName\AddressLoad", "SpaceBetween1", null);
if (value != null)
{
    if (value == "True")
    {
        checkBox1.Checked = true;
    } Else {
        checkBox1.Checked = false;
    }
}
This works but I feel there is probably a better way to do it.
I tried this
checkBox1.Checked = (Boolean)Registry.GetValue(@"HKEY_CURRENT_USER\Software\CompanyName\AddressLoad", "SpaceBetween1", null);
But it gives me a "Specified cast is not valid." error.
The value is being stored as REG_SZ in the registry. Not sure if that is causing he issue.

I have searched for how to resolve this but have not found a case where it has been done this way.
Is there a better way to cast a string value to boolean and assign it to a checkbox?
Since the type of the value that you read from the registry is a string, you cannot cast it. However, you can convert it:
checkBox1.Checked = Convert.ToBoolean(
    Registry.GetValue(
        @"HKEY_CURRENT_USER\Software\CompanyName\AddressLoad"
    ,   "SpaceBetween1"
    ,   null
    )
);
                        Use Convert.ToBoolean, since Registry.GetValue will return an object and if it is of type bool or if it contains string true/false, you will get the result. 
For example:
object obj = "true";
bool b = (bool) obj; //This will fail
bool b2 = Convert.ToBoolean(obj); //This will work. 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With