代码如下
private void Button1_Click(object sender, System.EventArgs e)
{
SqlConnection1 = new SqlConnection(ConfigurationSettings.AppSettings[ "Conn "]);
SqlCommand1=new SqlCommand( "select * from S_Manager where UserName=@UserName and PassWord=@PassWord
",SqlConnection1);
SqlCommand1.CommandType=CommandType.StoredProcedure;
SqlCommand1.Parameters.Add(new SqlParameter( "@UserName ", SqlDbType.Char,240));
SqlCommand1.Parameters[ "@UserName "].Value =UserName1.Text;
SqlCommand1.Parameters.Add(new SqlParameter( "@PassWord ", SqlDbType.NChar,240));
SqlCommand1.Parameters[ "@PassWord "].Value =PassWord1.Text;
try
{
SqlConnection1.Open();
SqlDataReader1=SqlCommand1.ExecuteReader(); }
catch
{
Response.Write( " <script> alert( '数据库操作错误! ') </script> ");
}
if(SqlDataReader1.Read()==true)
{
Session[ "UserName "]=UserName1.Text;
SqlConnection1.Close();
Response.Redirect( "Default.aspx ");
}
else
{
SqlDataReader1.Close();
SqlConnection1.Close();
Response.Write( " <script> alert( '您输入的用户名或密码错误,请重新登陆! ') </script> ");
}
}
出现的错误为
System.NullReferenceException: 未将对象引用设置到对象的实例。
if(SqlDataReader1.Read()==true)
------解决方法--------------------------------------------------------
可能是SqlDataReader1=SqlCommand1.ExecuteReader();没有返回值,你跟踪下看看
------解决方法--------------------------------------------------------
改成这样SqlCommand1=new SqlCommand( "select * from S_Manager where UserName= '@UserName ' and PassWord= '@PassWord '
",SqlConnection1);
------解决方法--------------------------------------------------------
这种错误说明SqlDataReader1为空,可检查用户名和密码是否错误。在前面的代码设置断点察看下。
还有你前面创建sqlcommand的时候既然指定了sql语句,为什么'SqlCommand1.CommandType=CommandType.StoredProcedure;'?
这句是将命令的类型指定为存储过程,可修改为SqlCommand1.CommandType=CommandType.
Text;
------解决方法--------------------------------------------------------
SqlCommand1.CommandType=CommandType.StoredProcedure;
==> SqlCommand1.CommandType=CommandType.Text;
SqlDataReader SqlDataReader1;
------解决方法--------------------------------------------------------
你既然制定了SQL语句,就没有必要写这句话了'SqlCommand1.CommandType=CommandType.StoredProcedure;'