Try using New
in your List(of SqlCommand)
declaration:
Dim PendingSQLChanges As New List(Of SqlCommand)
It was not instantiated thus the Null Reference
.
Pergunta
I have a form with information pulled from SQL that can be edited, once the form is closed I want to either write any changes back to the database or discard them. I don't want to store two sets of the data for comparison and I don't want to re-query SQL for the same.
I came up with the idea of creating a List of SQLCommand items and processing them if changes are to be saved however I get the following error when trying to add a SQLCommand to the list:
An unhandled exception of type 'System.NullReferenceException' occurred in Application1.exe
Additional information: Object reference not set to an instance of an object.
I've probably missed something really simple but I can't see what myself.
My code is below:
Public Class frm1
Public Property ContID As String
Dim PendingSQLChanges As List(Of SqlCommand)
Private Sub btnAddTel_Click(sender As Object, e As EventArgs) Handles btnAddTel.Click
Using x As New SqlCommand("INSERT into ContactTels (Tel, CoID) Values (@NewValue, @ContID) ;--", cnn)
x.Parameters.Add("@NewValue", SqlDbType.NVarChar, 100).Value = strNewvalue
x.Parameters.Add("@ContID", SqlDbType.Int).Value = ContID
PendingSQLChanges.Add(x) <This is the line I get the error on.
btnSave.Enabled = True
End Using
End Sub
As you can see I am adding parameters to the SQLCommand otherwise I would have used a List of strings containing the SQLCommand.Commandtext and used that later.
If I can get the list working the code I will use to process the saved commands is:
For x = 0 To PendingSQLChanges.Count - 1
PendingSQLChanges(x).ExecuteNonQuery()
Next
Is that correct as well?
Solução
Try using New
in your List(of SqlCommand)
declaration:
Dim PendingSQLChanges As New List(Of SqlCommand)
It was not instantiated thus the Null Reference
.