保存并加载单选按钮的值';t工作c#
我正在用C#编写一个软件,其中我使用regedit来存储用户的一些偏好。首选项之一是:选中哪个单选按钮。这就是它的样子:保存并加载单选按钮的值';t工作c#,c#,.net,radio-button,C#,.net,Radio Button,我正在用C#编写一个软件,其中我使用regedit来存储用户的一些偏好。首选项之一是:选中哪个单选按钮。这就是它的样子: String readPreference = (String)Registry.GetValue(RegLocation, "Preference", "true;false"); var temp = readPreference.Split(new string[] { ";" }, StringSplitOptions.None); radioButton1.Chec
String readPreference = (String)Registry.GetValue(RegLocation, "Preference", "true;false");
var temp = readPreference.Split(new string[] { ";" }, StringSplitOptions.None);
radioButton1.Checked = bool.TryParse(temp[0], out tempBool);
radioButton2.Checked = bool.TryParse(temp[1], out tempBool);
但无论temp[0]和temp[1]的值如何,RadioButton1.Checked
将始终变为false,RadioButton2.Checked
将始终变为true
以下是两种可能的情况,第一种:
temp[0] = false;
temps[1] = true;
radioButton1.Checked = temp[0] //it's supposed to become false but it stays true
radioButton2.Checked = temp[1] //it becomes true
因此,radioButton1.Checked
变为false,radioButton2.Checked
保持为true
第二条:
temp[0] = true;
temps[1] = false;
radioButton1.Checked = temp[0] //it becomes true
radioButton2.Checked = temp[1] //it becomes false
但随后,radioButton1.Checked
变为false,radioButton2.Checked
变为true
这是怎么可能的,又是怎么解决的?我认为问题出在下面的代码中-
radioButton1.Checked = bool.TryParse(temp[0], out tempBool);
radioButton2.Checked = bool.TryParse(temp[1], out tempBool);
bool.TryParse
如果能够成功地将第一个参数解析为bool值,它将始终返回true。你需要做的是
bool tempBool_1 = false, tempBool_2 = false;
if(bool.TryParse(temp[0], out tempBool_1))
{
radioButton1.Checked = tempBool_1;
}
else
{
// handle parsing error.
}
if(bool.TryParse(temp[0], out tempBool_2))
{
radioButton2.Checked = bool.TryParse(temp[1], out tempBool_2);
}
else
{
// handle parsing error.
}
我刚刚替换了
radioButton1.Checked=bool.TryParse(temp[0],out tempBool)代码>通过radioButton1.Checked=Convert.ToBoolean(温度[0])代码>并且它可以工作是的,这也应该可以工作。但是,如果出于某种原因,您希望注册表中的值可能会损坏,那么Convert.ToBoolean()
将在无法解析值时引发异常。如果捕获到异常,值将设置为默认值,因此不会有任何问题。