在工程中,我建了一个类,用来写一些公共的方法,下面是用于数据库连接的一个方法。由于在类中引用不到Application,故通过参数page间接调用Application,但是在调试中存在一个问题,objPage.Application[ "DBConn "]此调用经常出错,弹出的错误提示为:Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
请教各位大侠,看看问题出在哪里。附加代码如下:
public static SqlConnection DBConnection(Page objPage)
{
SqlConnection objConn;
if(objPage.Application[ "DBConn "] == null)
{
string strConnection = ConfigurationSettings.AppSettings[ "SqlSvrIP "].ToString();
objConn = new SqlConnection(strConnection);
objConn.Open();
objPage.Application[ "DBConn "] = objConn;
}
else
{
objConn = (SqlConnection)objPage.Application[ "DBConn "];
}
return objConn;
}
------解决方案--------------------------------------------------------
public static SqlConnection DBConnection(SqlConnection DBConn)
{
SqlConnection objConn;
if(DBConn == null)
{
string strConnection = ConfigurationSettings.AppSettings[ "SqlSvrIP "].ToString();
objConn = new SqlConnection(strConnection);
objConn.Open();
}
else
{
objConn =DBConn;
}
return objConn;
}
===================================================
在调用的时候
先把Application转化为SqlConnection传过去.
调用完之后在给Application从新赋值.