日期:2014-05-18  浏览次数:20729 次

未将对象引用设置到对象的实例问题
异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。

源错误: 


行 100: }
行 101: List<EducationClass> List_EducationClass = new List<EducationClass>();
行 102: while (rec.Read())(这里出错了)
行 103: {
行 104: EducationClass EducationClass = new EducationClass();
 

运行时没有错误,但是只要点击菜单超过七次马上就出现这个问题了,不明白原因,是缓存的问题还是代码的问题?

代码:

 /// <summary>
  /// 查看全部分类
  /// </summary>
  /// <param name="nClassID"></param>
  /// <returns></returns>
  public List<EducationClass> Get_EducationClass(int nParentID)
  {
  SQLHelper.SQLHelper sqlHelper = new SQLHelper.SQLHelper();
  SqlParameter[] ParamList ={ 
  sqlHelper.CreateInParam("@ParentID",SqlDbType.Int,4,nParentID)
  };
  SqlDataReader rec = null;
  try
  {
  sqlHelper.RunProc("Get_EducationClass", ParamList, out rec);
  }
  catch (Exception ex)
  {
  SystemError.CreateErrorLog(ex.Message);
  throw new Exception(ex.Message, ex);
  }
  List<EducationClass> List_EducationClass = new List<EducationClass>();
  while (rec.Read())
  {
  EducationClass EducationClass = new EducationClass();
  EducationClass.ClassID = Int32.Parse(rec["ClassID"].ToString());
  EducationClass.ClassName = rec["ClassName"].ToString();
  EducationClass.ParentID = Int32.Parse(rec["ParentID"].ToString());
  EducationClass.ParentOrder = Int32.Parse(rec["ParentOrder"].ToString());
  List_EducationClass.Add(EducationClass);
  EducationClass = null;
  }
  return List_EducationClass;
  }


------解决方案--------------------

你要按照流程来,
先打开连接,
再执行命令
再关闭连接
try
{
//打开连接
...
///读取数据
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch(Exception ex)
{
dataReader = null;
///记录错误日志
SystemError.CreateErrorLog(ex.Message);
}
finally
{
关闭连接
}
看你代码每次都没关闭连接