Boolean cast The specified cast is not a valid error

I am currently saving true / false checkbox. I checked the value in the registry until reset the next time the form loads.

When the form is loaded, I get the value and check this box.

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 that probably the best way to do this.

I tried this

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

But that gives me an error "Specified cast is not valid.".

The value is stored in REG_SZ in the registry. Not sure if it caused him.

enter image description here

I searched how to resolve it, but did not find a case when it was done this way.

Is there a better way to make a string value for boolean and assign it to a checkbox?

+4
source share
4 answers

, , string, . :

checkBox1.Checked = Convert.ToBoolean(
    Registry.GetValue(
        @"HKEY_CURRENT_USER\Software\CompanyName\AddressLoad"
    ,   "SpaceBetween1"
    ,   null
    )
);
+7

Convert.ToBoolean, Registry.GetValue object, bool true/false, .

:

object obj = "true";
bool b = (bool) obj; //This will fail
bool b2 = Convert.ToBoolean(obj); //This will work. 
+6

REG_SZ- it is string.

With that in mind, you can do

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

Source: https://habr.com/ru/post/1615271/


All Articles