c# - 保存和加载单选按钮的值不起作用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
成为真实
这怎么可能,如何解决?
解决方案
我认为问题出在以下代码中-
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.
}
推荐阅读
- dart - Flutter:如何布局类似于 tabbar 的 spaceBetween
- python - 从 3-D numpy 数组中选择元素
- amazon-web-services - AWS Cognito:即使电子邮件/电话未验证,用户也显示确认
- javascript - 如何在角度 5 中单击滚动条时触发事件
- mysql - 在 SQL 中反馈 NULL 值
- flask - eve对子文档的CRUD操作
- javascript - 在 React 中使用 Stripe 和 Axios 链接异步函数调用
- paypal - 实施点对点支付
- javascript - 在现有 HTML CSS 网站中使用 Vue.js 时,div 的排列不符合预期
- c# - 如何从 C# 控制台应用程序导出 csv 文件中的数据?