大家看我写的方法:
private int Id = 0;
public string execteGetReturn(string strSql)
{
//创建连接conn
……
cmd.Connection = conn;
cmd.CommandText = strSql;
string result = (string)cmd.ExecuteScalar();
return result;
}
public void getID()
{
string strSql="select id from voteConfig";
Id = int.Parse(this.execteGetReturn(strSql)); }
结果预览:出现下面的错误:
无法将类型为“System.Int32”的对象强制转换为类型“System.String”。
行 24: string strSql="select id from voteConfig";
行 25: Id = int.Parse(db.execteGetReturn(strSql));
行 26:
行 27: }
请问高手们,如何会出现这种情况呢?如何解决呢?
private int Id = 0;
public string execteGetReturn(string strSql)
{
//创建连接conn
……
cmd.Connection = conn;
cmd.CommandText = strSql;
string result = (string)cmd.ExecuteScalar();
return result;
}
public void getID()
{
string strSql="select id from voteConfig";
Id = int.Parse(this.execteGetReturn(strSql)); }
结果预览:出现下面的错误:
无法将类型为“System.Int32”的对象强制转换为类型“System.String”。
行 24: string strSql="select id from voteConfig";
行 25: Id = int.Parse(db.execteGetReturn(strSql));
行 26:
行 27: }
请问高手们,如何会出现这种情况呢?如何解决呢?
Id = int.Parse(db.execteGetReturn(strSql))不是把string类型转换成int类型么?
为啥提示错误里说是int转换成string呢?
这句,改为:
string result = Convert.ToString(cmd.ExecuteScalar());
string strSql = "select id from voteConfig";
SqlConnection conn = new SqlConnection(此处写连接数据库字符串);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
da.Fill(ds);
int id = Convert.ToInt32(ds.Tables[0].Rows[0]["Id"].ToString());
问一下:为什么是怎么的呢?
string result = (string)cmd.ExecuteScalar(); 和
string result = Convert.ToString(cmd.ExecuteScalar());
不都是强制转换,那有什么区别呢?为什么有写错误编译的时候没问题,预览的时候就出线了呢?
改为int Id;
if( int.TryPase(db.execteGetReturn(strSql),out Id) )
{
}
你调试下看看这个 result 到时是不是数字啊?
还有this.execteGetReturn(strSql)与db.execteGetReturn(strSql)是一样的吗
考虑下面的代码,它是会出错的:
int i = 3;
object o = i;
string s = (string)o;