首页 > 解决方案 > 保存和加载单选按钮的值不起作用c#

问题描述

我正在用 C# 编写一个软件,在其中我使用 regedit 来存储用户的一些偏好。其中一项偏好是:选中哪个单选按钮。这就是它的外观:

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总是会变为假,并且RadioButton2.Checked总是会变为真。

以下是两种可能的情况,第一种:

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变得虚假并radioButton2.Checked保持真实。

第二个:

temp[0] = true;
temps[1] = false;
radioButton1.Checked = temp[0] //it becomes true
radioButton2.Checked = temp[1] //it becomes false

但随后,radioButton1.Checked变得虚假并radioButton2.Checked成为真实

这怎么可能,如何解决?

标签: c#.netradio-button

解决方案


我认为问题出在以下代码中-

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.
}

推荐阅读