mardi 10 novembre 2015

Boolean cast Specified cast is not 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.

enter image description here

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?




Aucun commentaire:

Enregistrer un commentaire