【问题标题】:Object reference not set to an instance of an object. NullReferenceException occured [duplicate]你调用的对象是空的。发生 NullReferenceException [重复]
【发布时间】:2013-10-03 19:48:38
【问题描述】:

我是 .Net 的新手,不知道如何解决我的大部分问题。这是我的问题。我创建了一个表单来执行脚本列表。数据将来自数据库。我的问题是,当我调试时,我在此代码块上收到 NullReferenceException 错误

private void Load_RefreshForm_ScriptMgmt()
{
    try
    {
        SqlCommand ObjCmd = new SqlCommand();
        SqlConnection ObjConn = new SqlConnection();
        this.Ds_Settings1.Tables["Settings_RefreshForm_ScriptMgmt_SelectALL"].Clear();
        ObjConn.ConnectionString = this.MainConnection;
        ObjCmd.CommandType = CommandType.StoredProcedure;
        ObjCmd = new SqlCommand(this.da_LoadScripts.SelectCommand.CommandText.ToString(), ObjConn);
        this.da_LoadScripts.SelectCommand = ObjCmd;
        this.da_LoadScripts.Fill(this.Ds_Settings1);
    }
    catch (Exception exception)
    {
        ProjectData.SetProjectError(exception);
        this.DisplayOnly_ErrorHandler("ERROR LOADING REFRESH SCRIPTS ", exception.Message, MsgBoxStyle.Critical);
        ProjectData.ClearProjectError();
    }
}

【问题讨论】:

  • this.da_LoadScripts.SelectCommand 在用ObjCmd 覆盖之前首先设置在哪里?如果在您第一次创建和设置ObjCmd 时它为空,那么您将通过尝试访问CommandText 属性得到一个空异常。您应该能够通过调试您的应用来确定错误发生的确切位置。
  • 欢迎来到 Stack Overflow!几乎所有NullReferenceException 的情况都是一样的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。

标签: c# winforms nullreferenceexception


【解决方案1】:

您可以通过在 try 块的第一行设置断点并跟踪执行来查看哪一行引发了该异常。

有很多行可以抛出该异常。 this.Ds_Settings1 可以为空,this.da_LoadScripts 也可以。 如果其中一个对象为 null,并且您尝试对其调用函数或访问属性,则会收到该错误。在调用该函数之前验证这些对象是否已定义。

【讨论】:

    【解决方案2】:

    您可以通过在“异常”窗口中启用中断执行来轻松跟踪哪个语句引发了此异常:

    调试 > 异常... (Ctrl + Alt + E)

    并选中 Common Language Runtime Exceptions 'Thrown' 复选框。

    至于异常本身 - 它非常不言自明 - 您正在尝试使用未分配给任何东西的引用变量(无处指向)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 2012-01-02
      • 2013-05-27
      • 2013-07-22
      相关资源
      最近更新 更多