CommandBuilder 개체를 사용할 때 System.NullReferenceException이 발생합니다.

이 문서는 개체를 사용할 CommandBuilder 때 발생하는 예외를 System.NullReferenceException resolve 데 도움이 됩니다.

원래 제품 버전: Visual Basic .NET
원래 KB 번호: 310367

증상

개체를 사용하여 개체에 CommandBuilder 대한 DataAdapter 명령을 다음과 같이 명시적으로 가져오는 경우:

da.InsertCommand = cb.GetInsertCommand

그런 다음, 다음 Visual Basic .NET 코드를 실행합니다.

cb.DataAdapter = Nothing

에 추가하는 DataAdapter 명령이 삭제되고 다음과 같은 오류 메시지가 표시됩니다.

app_name.exe 'System.NullReferenceException' 형식의 처리되지 않은 예외가 발생했습니다.
추가 정보: 개체 참조가 개체의 instance 설정되지 않았습니다.

원인

CommandBuilder 는 에서 연결 DataAdapter.CommandBuilder 이 해제되고 연결될 때 생성되는 명령을 삭제합니다 DataAdapter . 연결이 해제되거나 연결이 해제되면 명령이 null이 됩니다. 이 문제는 처음부터 빌드하는 명령에 영향을 주지 않습니다.

해결 방법

다음 방법 중 하나를 사용하여 이 문제를 resolve.

  • 에서 DataSetCommandBuilder 연결 해제하지 마세요.
  • 코드 또는 Visual Data Tools를 통해 직접 명령을 빌드합니다.

상태

이것은 의도적으로 설계된 동작입니다.

동작을 재현하는 단계

  1. 새 Visual Basic .NET Windows 애플리케이션 프로젝트를 만듭니다. Form1은 기본적으로 프로젝트에 추가됩니다.

  2. Form1에 단추 컨트롤을 추가합니다.

  3. 코드 보기로 전환하고 다음 코드를 코드 창의 맨 위에 추가합니다.

    Imports System.Data.OleDb
    Imports System.Data.SqlClient
    
  4. 단추의 이벤트에 다음 코드를 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.
    
  5. 사용자 환경에 맞게 연결 문자열 수정합니다.

  6. F5 키를 눌러 애플리케이션을 컴파일하고 실행합니다.