相关文章推荐
气宇轩昂的萝卜  ·  Request Body got ...·  1 年前    · 

本文可帮助你解决 System.NullReferenceException 使用 CommandBuilder 对象时发生的异常。

原始产品版本: Visual Basic .NET
原始 KB 编号: 310367

如果使用该 CommandBuilder 对象显式获取对象的命令, DataAdapter 如下所示:

da.InsertCommand = cb.GetInsertCommand

然后,运行以下 Visual Basic .NET 代码:

cb.DataAdapter = Nothing

添加到其中的 DataAdapter 命令将被删除,你将收到以下错误消息:

app_name.exe中出现了“System.NullReferenceException”类型的未经处理的异常
其他信息:对象引用未设置为对象的实例。

CommandBuilder 删除与 a 解除关联 DataAdapter.CommandBuilderDataAdapter 链接时生成的命令;未链接或取消关联时,命令为 null。 此问题不会影响从一开始就生成的命令。

使用以下方法之一来解决此问题:

  • 不要CommandBuilderDataSet脱离。
  • 在代码中或通过 Visual Data Tools 自行生成命令。
  • 此行为是设计使然。

    重现行为的步骤

  • 创建新的 Visual Basic .NET Windows 应用程序项目。 默认情况下,Form1 将添加到项目中。

  • 将按钮控件添加到 Form1。

  • 切换到“代码”视图,并将以下代码添加到“代码”窗口的顶部:

    Imports System.Data.OleDb
    Imports System.Data.SqlClient
    
  • 将以下代码添加到 Click 按钮的事件:

    Dim con As New SqlConnection("server=myserver;uid=sa;pwd=mypassword;" & _
                                "database=northwind")
    Dim da As New SqlDataAdapter("Select * From Customers", con)
    Dim cb As New SqlCommandBuilder(da)
    Dim cmdInsert As New SqlCommand( _
            "Insert Into Customer (CustomerID) Value ('AAAAA')", con)
    da.InsertCommand = cmdInsert
    da.UpdateCommand = cb.GetUpdateCommand
    da.DeleteCommand = cb.GetDeleteCommand
    Debug.WriteLine(da.InsertCommand.CommandText)
    Debug.WriteLine(da.DeleteCommand.CommandText)
    cb.DataAdapter = Nothing ' Comment out this line to avoid the error.
    cb = Nothing
    Debug.WriteLine(da.InsertCommand.CommandText)
    Debug.WriteLine(da.DeleteCommand.CommandText)'Error occurs here.
    
  • 根据环境修改连接字符串。

  • 按 F5 进行编译并运行应用程序。

  •