gpt4 book ai didi

c# - 无法将类型 'string' 隐式转换为 'bool' CheckBox

转载 作者:太空宇宙 更新时间:2023-11-03 18:34:19 33 4
gpt4 key购买 nike

我正在尝试从 VB.Net 转换为 C# 以从 sql 数据库读取数据。以下代码给我一个错误。“无法将类型‘string’隐式转换为‘bool’”。它在 VB 中工作得很好。如何将此语句转换为 C#?

chkNewEmployee.Checked = dr["chkNewEmployee"].ToString();

最佳答案

chkNewEmployee.Checked = Convert.ToBoolean(dr["chkNewEmployee"]);

ToBoolean :

true or false, which reflects the value returned by invoking the IConvertible.ToBoolean method for the underlying type of value. If value is null, the method returns false.

根据您的需要,您可能想尝试 bool.Parsebool.TryParse

更新

bool.Parse , bool.TryParseConvert.ToBoolean :

  • 不区分大小写
  • 忽略前导和尾随空格

bool.Parse :

  • 正确的truefalse
  • 在转换失败时抛出 FormatException

bool.TryParse :

  • 正确的truefalse
  • 在转换失败的情况下不抛出异常
  • 如果转换成功返回true,否则返回false
  • 转换结果通过第二个参数保存(out bool result)

Convert.ToBoolean :

  • 正确的truefalsenull(返回false null)
  • 的情况
  • 在转换失败时抛出 FormatException

关于c# - 无法将类型 'string' 隐式转换为 'bool' CheckBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17598366/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com