Hi there guys,

I have a code in VB.net that is subtracting the items sold from the stock in the database

When the program is run and the neccesary input are provided on the form and when the sale button is clicked the program is throwing an erroe message "Object reference not set to an instance" on line 8. However, despite the error, it is successfully updating the table with the new stock quantity.
Below is the code am using

rivate Sub btnCompltSale_Click(sender As Object, e As EventArgs) Handles btnCompltSale.Click
        Dim cn As New SqlClient.SqlConnection("Data Source=localhost;Initial Catalog=easysales;Integrated Security=True")
        Try
            cn.Open()

            For Each Isold As DataGridViewRow In dataviewSales.Rows
                Dim Barcode As String
                Dim Inveupdate As New SqlClient.SqlCommand

                barcode = Isold.Cells(0).Value.ToString()

                Inveupdate.CommandText = "UPDATE tblItems SET Quantity = Quantity - 1 WHERE Barcode=@Barcode"

                Inveupdate.Parameters.AddWithValue("@Barcode", Isold.Cells(0).Value.ToString())

                Inveupdate.CommandType = CommandType.Text
                Inveupdate.Connection = cn
                Inveupdate.ExecuteNonQuery()
                Inveupdate.Parameters.Clear()
                Inveupdate.Dispose()

            Next

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

The loop restricts you to create a new instance of a SQLCommand objects as same qualified name which you already disposed it.

Create a single instace before calling the loop and dispose it after completing the loop.

Your codes should be

Dim Inveupdate As New SqlClient.SqlCommand
Inveupdate.CommandType = CommandType.Text
Inveupdate.Connection = cn

For Each Isold As DataGridViewRow In dataviewSales.Rows
    Dim Barcode As String
    barcode = Isold.Cells(0).Value.ToString()

    Inveupdate.CommandText = "UPDATE tblItems SET Quantity = Quantity - 1 WHERE Barcode=@Barcode"
    Inveupdate.Parameters.AddWithValue("@Barcode", Isold.Cells(0).Value.ToString())

    Inveupdate.ExecuteNonQuery()
    Inveupdate.Parameters.Clear()

Next
Inveupdate.Dispose()