我写了如下一段代码,但是调试时当我点击确定的时候老是出现未将对象引用设置到对象的实例。错误的行的是int flag=(int)co.ExecuteScalar();
整段代码如下: private void BT_Submit_Click(object sender, System.EventArgs e)
{
string strconn="server=(local);database=ELECT;Uid=ASPNET;Pwd=;Integrated Security=SSPI;";
SqlConnection conn=new SqlConnection(strconn);
//接收参数
string UName=TB_UName.Text.ToString().Trim();
string UPass=TB_UPass.Text.ToString().Trim();
string URole=DDL_Role.SelectedItem.Value.Trim();
//身份为学生
if(URole=="Student")
{
string SelectStr="Select * from Student where SName='"+TB_UName+"'and SPass='"+TB_UPass+"'";
SqlCommand comm=new SqlCommand(SelectStr,conn);
conn.Open();
int flag=(int) comm.ExecuteScalar();
conn.Close();
if(flag>0)
{
Session["UName"]=UName;
Session["URole"]=URole;
Response.Redirect("Student.aspx");
}
}
//身份为教师
if(URole=="Tecaher")
{
string SelectStr="Select * from Teaceher where TName='"+TB_UName+"'and TPass='"+TB_UPass+"'";
SqlCommand com=new SqlCommand(SelectStr,conn);
conn.Open();
int flag=(int)com.ExecuteScalar();
conn.Close();
if(flag>0)
{
Session["UName"]=UName;
Session["URole"]=URole;
Response.Redirect("Teacher.aspx");
}
}
// 身份为管理员
if(URole=="Admin")
{
string SelectStr="Select * from AUser where UName='"+TB_UName+"'and UPass='"+TB_UPass+"'";
SqlCommand co=new SqlCommand(SelectStr,conn);
conn.Open();
int flag=(int)co.ExecuteScalar();
conn.Close();
if(flag>0)
{
Session["UName"]=UName;
Session["URole"]=URole;
Response.Redirect("Aframe.aspx");
}
}

 

解决方案 »

  1.   

    to : string SelectStr="Select * from Student where SName='"+TB_UName+"'and SPass='"+TB_UPass+"'";
    int flag=(int) comm.ExecuteScalar();你用的是Select * from ....,所以返回的是一個數據集,不一定是int值的單一變量,所以你用
    int flag=(int) comm.ExecuteScalar();當然就不行了。
    應該用SqlCommand.ExecuteNonQuery (),它傳回的是命令影響的資料列數目。
      

  2.   

    说明string SelectStr="Select * from AUser where UName='"+TB_UName+"'and UPass='"+TB_UPass+"'";这句没有取到任何数据
      

  3.   

    ExecuteScalar()是取库中的某个值,也可以按表达式来取,这里应该用ExecuteScalar();并用SqlDataAdapter将其fill进dataset
      

  4.   

    楼上的非正解是因为你的select语句返回的结果集可能为空,所以executescalar方法返回一个空引用,在你显式地将空引用转换成int类型的时候就发生了你所说的错误希望我的答案能让你满意:)
      

  5.   

    可能就是  SQL语句使用的不当