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);
就能正常运行,谁能告诉我?先谢谢了

解决方案 »

  1.   

    将SqlCommand logincmd=new SqlCommand("select userid from tuser where username='"+this.tbxusername.Text+"' and userpwd='"+this.tbxpwd.Text+"'",con);的string 复制下来到查询分析器中运行一下看看
      

  2.   

    select userid 查不到数据时返回null,此时(int)logincmd.ExecuteScalar();会报错
    而select count(userid)查不到数据时返回的是0,此时(int)logincmd.ExecuteScalar();可以正常运行
      

  3.   

    应该是找不到记录,你怎么能转换成int型呢?
    object obj = logincmd.ExecuteScalar();
    if (obj != DBNull.Value)
    {
      int userid=(int)obj;
    }
    else
    {
      Response.Write("失败");
    }
      

  4.   

    mabaolin说的我试过了,没问题,但在.net中就不可以。谢谢了。
      

  5.   

    lxcnn说的,在我数据库中有数据的时候也是不可以,不仅仅是在没有数据的时候。谢谢了