Incorrect code sample in "SqlDataAdapter.UpdateCommand Property" documentation (319387)



The information in this article applies to:

  • Microsoft ADO.NET (included with the .NET Framework)
  • Microsoft Visual Basic .NET (2002)
  • Microsoft ADO.NET (included with the .NET Framework 1.1)
  • Microsoft Visual Basic .NET (2003)

This article was previously published under Q319387

SUMMARY

The SqlDataAdapter.UpdateCommand Property MSDN documentation and the "SqlDataAdapter.UpdateCommand Property" topic in the Microsoft Visual Studio .NET Help documentation describe how to get or how to set a Transact-SQL statement to update records in a data source by using the UpdateCommand property of a SqlDataAdapter object. This documentation includes the following code, which creates a SqlDataAdapter and sets some of the properties of the SqlDataAdapter:
Public Sub CreateSqlDataAdapter()

    Dim mySelectText As String = "SELECT * FROM Categories ORDER BY CategoryID"
    Dim mySelectConn As String = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind"
    Dim myDataAdapter As New SqlDataAdapter(mySelectText, mySelectConn)
    myDataAdapter.UpdateCommand.CommandText = "UPDATE Categories SET Description='Cheeses, Milk, Ice Cream' WHERE CategoryName='Dairy Products'"
    myDataAdapter.UpdateCommand.Connection = CType(myDataAdapter.SelectCommand.Connection, SqlConnection)

End Sub 'CreateSqlDataAdapter
				
When you run the code, you receive a System.NullReferenceException exception with the following error message:
Object reference not set to an instance of an object.

MORE INFORMATION

The SqlDataAdapter.UpdateCommand property is a SqlCommand object. Because this example does not create an instance of the UpdateCommand property, you cannot access its properties.

To resolve this problem, replace the last two lines of code in the Sub CreateSqlDataAdapter() procedure with the following code:
Dim updateCmd As New SqlCommand()
updateCmd.CommandText = "UPDATE Categories SET Description='Cheeses, Milk, Ice Cream' WHERE CategoryName='Dairy Products'"
updateCmd.Connection = CType(myDataAdapter.SelectCommand.Connection, SqlConnection)
myDataAdapter.UpdateCommand = updateCmd
				

Modification Type:MinorLast Reviewed:9/15/2005
Keywords:kbvs2002sp1sweep kbbug kbDataAdapter kbdocerr kbpending KB319387