The specified Boolean conversion is not a valid error


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(
    ,   "SpaceBetween1"
    ,   null