指定的转换无效。error code: dr.Read();
mainfrm.menuItem1.Visible = (bool)(dr.GetValue(1));
source code: MainForm mainfrm = new MainForm();
mainfrm.Tag = this.FindForm();
string name = this.txtUser.Text.Trim(); string a = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
string Sql = "select *from tb_role where name ='"+name+"'";
SqlConnection conn = new SqlConnection(a);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn); SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
mainfrm.menuItem1.Visible = (bool)(dr.GetValue(1));request method: mainfrm.menuItem1.Visible = bool.parse(dr.GetValue(1)); not correct mainfrm.menuItem1.Visible =convert .toboolean(dr.GetValue(1)); not correct
mainfrm.menuItem1.Visible = (bool)(dr.GetValue(1));
source code: MainForm mainfrm = new MainForm();
mainfrm.Tag = this.FindForm();
string name = this.txtUser.Text.Trim(); string a = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
string Sql = "select *from tb_role where name ='"+name+"'";
SqlConnection conn = new SqlConnection(a);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn); SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
mainfrm.menuItem1.Visible = (bool)(dr.GetValue(1));request method: mainfrm.menuItem1.Visible = bool.parse(dr.GetValue(1)); not correct mainfrm.menuItem1.Visible =convert .toboolean(dr.GetValue(1)); not correct
解决方案 »
- 请大家帮我解释下这段C#代码
- C#下使用SendMessageW 的WM_GETTEXT不能工作 VS2005环境
- 如何在填充DataGridView时改变某列的值?
- excel自定义菜单事件问题。
- DataList控件的问题
- 为什么我的条件查询不能完整地将数据库中符合条件的记录返回在dataGirdView中?
- SQL Server2005数据删了一条数据,可不可以恢复啊?
- winform下如何修改TreeView滚动条的颜色
- 创建两个包含OCX控件的窗体实例后,关闭时无法响应的问题?
- 大家搞到没有?amazon 5星的C#书,C# HOW TO PROGRAM ,哈哈,太爽了,散分.
- 关于金蝶K3 BOS 的设计思想?
- 求一正则 验证一个字符串是否包含特殊字符(除数字字母和下划线以外所有字符)
查看了相前的例子还是不会改/但在网上查看例子时:想当然的认为 Convert.ToBoolean("1")==true ,结果抛出如下错误:
该字符串未被识别为有效的布尔值。检查 System.Convert.ToBoolean(String) 方法,代码如下:
public static bool ToBoolean(string value)
{
if (value == null)
{
return false;
}
return bool.Parse(value);
}显然与System.Boolean.Parse(String) 相关,代码如下:
public static bool Parse(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (string.Compare(value, bool.TrueString, true, CultureInfo.InvariantCulture) == 0)
{
return true;
}
if (string.Compare(value, bool.FalseString, true, CultureInfo.InvariantCulture) != 0)
{
value = value.Trim();
if (string.Compare(value, bool.TrueString, true, CultureInfo.InvariantCulture) == 0)
{
return true;
}
if (string.Compare(value, bool.FalseString, true, CultureInfo.InvariantCulture) != 0)
{
throw new FormatException(Environment.GetResourceString("Format_BadBoolean"));
}
}
return false;
}只要看看bool.TrueString就知道原因了
bool.TrueString = "True";
bool.FalseString = "False";难怪抛出了错误.看看System.Convert.ToBoolean(Int16)方法,代码如下:
public static bool ToBoolean(short value)
{
return (value != 0);
}因此可以改写为: Convert.ToBoolean(Convert.ToInt16("1"))由此看来System.Convert.ToBoolean(String)方法设计得还不是很厚道,大家说呢?