Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
MatthewD Avatar asked Nov 10 '15 15:11

MatthewD


2 Answers

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
    )
);
like image 60
Sergey Kalinichenko Avatar answered Oct 31 '22 01:10

Sergey Kalinichenko


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. 
like image 42
Habib Avatar answered Oct 31 '22 00:10

Habib