發生的錯誤:
未將對象引用設定到對象的執行個體。
說明: 執行當前 Web 請求期間,出現未處理的異常。請檢查堆疊追蹤資訊,以瞭解有關該錯誤以及代碼中導致錯誤的出處的詳細資料。
異常詳細資料: System.NullReferenceException: 未將對象引用設定到對象的執行個體。
源錯誤:
行 281: OleDbCommand myCommand11=new OleDbCommand(selCmd,myConn);
行 282: myCommand11.Connection.Open();
行 283: int flag=(int)myCommand11.ExecuteScalar();
行 284: myCommand11.Connection.Close();
行 285: if(flag!=0)
源檔案: e:\site\jiasheng\manager.aspx.cs 行: 283
堆疊追蹤:
[NullReferenceException: 未將對象引用設定到對象的執行個體。]
jiasheng.admin.manager.Chk_Pass() in e:\site\jiasheng\manager.aspx.cs:283
jiasheng.admin.manager.Button5_Click(Object sender, EventArgs e) in e:\site\jiasheng\manager.aspx.cs:246
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain() +1277
版本資訊: Microsoft .NET Framework 版本:1.1.4322.573; ASP.NET 版本:1.1.4322.573
原來的代碼:
private bool Chk_Pass()
{
string path=ConfigurationSettings.AppSettings["strConn2"];
string dataPath="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";";
OleDbConnection myConn=new OleDbConnection();
myConn.ConnectionString=dataPath;
string selCmd="select * from [user] where username='"+Session["UserName"].ToString()+"' and pass='"+tb_OldPass.Text+"'";
OleDbCommand myCommand11=new OleDbCommand(selCmd,myConn);
myCommand11.Connection.Open();
int flag=(int)myCommand11.ExecuteScalar();
myCommand11.Connection.Close();
if(flag!=0)
{
return true;
}
else
return false;
}
分析原因:
首先說明一下,如果在執行資料庫查詢的過程當中,username和pass都為正確的,那麼則不會發生此錯誤,如果username或者pass其中一者是錯的,則一定會出現此錯誤,分析了一下:
所引發的異常為NullReferenceException,證明myCommand11.ExecuteScalar()是一個Null 物件,當int flag=(int)myCommand11.ExecuteScalar(); 試圖把Null 物件轉化成int並賦值時,引發了此異常
解決辦法:
經過以上的分析得出:如果當myCommand11.ExecuteScalar()為一個Null 物件時,也就是select * from [user] where username='"+Session["UserName"].ToString()+"' and pass='"+tb_OldPass.Text+"'";
的結果為空白時,在程式中引發一個異常,可以用try....catch....finally來解決此問題。
修改後的代碼:
private bool Chk_Pass()
{
string path=ConfigurationSettings.AppSettings["strConn2"];
string dataPath="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";";
OleDbConnection myConn=new OleDbConnection();
myConn.ConnectionString=dataPath;
string selCmd="select * from [user] where username='"+Session["UserName"].ToString()+"' and pass='"+tb_OldPass.Text+"'";
OleDbCommand myCommand11=new OleDbCommand(selCmd,myConn);
myCommand11.Connection.Open();
try
{
int flag=(int)myCommand11.ExecuteScalar();
if(flag!=0)
{
return true;
}
else
return false;
}
catch
{
return false;
}
finally
{
myCommand11.Connection.Close();
} }
小結:
這個錯誤的出現,使我認識到:不能用一個Null 物件來給將來賦值的對象賦值,否則會引起NullReferenceException異常。