【问题标题】:Save and load the value of radio buttons doesn't work c#保存和加载单选按钮的值不起作用c#
【发布时间】:2018-08-30 04:33:10
【问题描述】:

我正在用 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 将始终为 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 变为假,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# .net radio-button


    【解决方案1】:

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

    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(temp[0]); 并且可以正常工作
    • 是的,应该也可以。但是,如果由于某种原因,您预计注册表中的值可能会损坏,那么Convert.ToBoolean() 将在无法解析该值时抛出异常。
    • 如果我发现异常,值会设置为默认值,所以不会有任何问题。
    猜你喜欢
    • 2017-10-24
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多