C#转换的一点烦人的有关问题,各位帮下忙System.InvalidCastException: 指定的转换无效
C#转换的一点烦人的问题,各位帮下忙System.InvalidCastException: 指定的转换无效。
string count = "select id from Comment_url where url='" + url + "' ";
SqlCommand cmd1 = new SqlCommand(count, conC);
int cc = (Int32)cmd1.ExecuteScalar();
Response.Write(cc.ToString());
为什么它会报System.InvalidCastException: 指定的转换无效。
哪位哥们帮下忙了
------解决方案--------------------
ExecuteScalar()本身就返回一个int, 为什么还要转换呢?
你确定查询返回的结果是唯一值吗?
------解决方案--------------------
试试:
首先确认cmd1.ExecuteScalar()不能为空!!!
如果为空,你进行(Int32)拆箱时,当然会出现这样错误.
string count = "select id from Comment_url where url='" + url + "' ";
SqlCommand cmd1 = new SqlCommand(count, conC);
int cc = (Int32)cmd1.ExecuteScalar();
Response.Write(cc.ToString());
为什么它会报System.InvalidCastException: 指定的转换无效。
哪位哥们帮下忙了
------解决方案--------------------
ExecuteScalar()本身就返回一个int, 为什么还要转换呢?
你确定查询返回的结果是唯一值吗?
------解决方案--------------------
试试:
首先确认cmd1.ExecuteScalar()不能为空!!!
如果为空,你进行(Int32)拆箱时,当然会出现这样错误.
- C# code
public static int ConvertToInt(string value) { ///数据为空,返回-1 if(string.IsNullOrEmpty(value))return -1; int result = -1; ///执行转换操作 Int.TryParse(value,out result); return result; }