异常详细信息:
System.NullReferenceException: 未将对象引用设置到对象的实例。private void btnsubmit_Click(object sender, System.EventArgs e)
{
SqlConnection con=db.dbcon();
con.Open();
SqlCommand logincmd=new SqlCommand( "select userid from tuser where username= ' "+this.tbxusername.Text+ " ' and userpwd= ' "+this.tbxpwd.Text+ " ' ",con);
int userid=(int)logincmd.ExecuteScalar();
if (userid> 0)
{
Response.Write( "成功 ");
}
else
{
Response.Write( "失败 ");
}
con.Close();
}
我的程序代码如上所示。tuser表的userid列为int型。这样执行程序时会出现如下错误代码:异常详细信息: System.NullReferenceException:
未将对象引用设置到对象的实例。
但将SqlCommand logincmd=new SqlCommand( "select userid from tuser where username= ' "+this.tbxusername.Text+ " ' and userpwd= ' "+this.tbxpwd.Text+ " ' ",con);代码改换为SqlCommand logincmd=new SqlCommand( "select count(userid) from tuser where username= ' "+this.tbxusername.Text+ " ' and userpwd= ' "+this.tbxpwd.Text+ " ' ",con);
就能正常运行,谁能告诉我?先谢谢了
------解决方案--------------------将SqlCommand logincmd=new SqlCommand( "select userid from tuser where username= ' "+this.tbxusername.Text+ " ' and userpwd= ' "+this.tbxpwd.Text+ " ' ",con);的string 复制下来到查询分析器中运行一下看看
------解决方案--------------------select userid 查不到数据时返回null,此时(int)logincmd.ExecuteScalar();会报错
而select count(userid)查不到数据时返回的是0,此时(int)logincmd.ExecuteScalar();可以正常运行
------解决方案--------------------应该是找不到记录,你怎么能转换成int型呢?
object obj = logincmd.ExecuteScalar();
if (obj != DBNull.Value)
{
int userid=(int)obj;
}
else
{
Response.Write( "失败 ");
}
------解决方案--------------------跟你数据库中有没有数据没关系,问题是你查询的结果是否取到数据了,设断点跟踪一下