MatthewD
MatthewD

Reputation: 6761

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?

Upvotes: 6

Views: 7866

Answers (4)

Sinatr
Sinatr

Reputation: 21998

REG_SZ is a string.

With that in mind you can do

checkBox1.Checked = Registry.GetValue(@"HKEY_CURRENT_USER\Software\CompanyName\AddressLoad",
    "SpaceBetween1", null).ToString() == "True";

Upvotes: 2

Habib
Habib

Reputation: 223312

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. 

Upvotes: 8

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

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
    )
);

Upvotes: 10

w.b
w.b

Reputation: 11238

Try to use Convert.ToBoolean:

https://msdn.microsoft.com/en-us/library/86hw82a3(v=vs.110).aspx

Upvotes: 4

Related Questions