0

I have a problem sending data to my access database.

I get this error

NullReferenceExeption was Unhandled - "Object reference not set to an instance of an object."on this part of my codemaxrows = ds.Tables("asdf").Rows.Count

What would that mean?

Here is my code :

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

    ID = TextID.Text
    FName = Textfname.Text
    LName = Textlname.Text
    If con.State = ConnectionState.Closed Then
        con.Open()
    End If

    If TextID.Tag & "" = "" Then
        cmd = New OleDbCommand("INSERT INTO asdf(ID,fname,lname) " & _
        "VALUES(' " & TextID.Text & "', '" & Textfname.Text & "', '" & Textlname.Text & "')", con)
        cmd.ExecuteNonQuery()
    Else
        cmd.CommandText = "UPDATE asdf" & _
        "SET ID=" & TextID.Text & _
        ", fname='" & Textfname.Text & "'" & _
        ",lname ='" & Textlname.Text & "'" & _
        ", WHERE ID =" & TextID.Tag
    End If

    btnClear.PerformClick()

    MessageBox.Show("Data successfully saved!")
    maxrows = ds.Tables("asdf").Rows.Count ' <---- Exception occurs here
    inc = 1
    con.Close()
    RefreshData()

End Sub
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • You get this error when you try to invoke a method on an object that is null. In this case it means either your data set ds or the table is null. – McGarnagle May 21 '12 at 03:33
  • how will i fix this error? im sorry im just new to vb programming. – Derick Baquilod Operario May 21 '12 at 03:45
  • 2
    Well, I'd start with the **ds** object. Where is it declared? I don't see it anywhere in the code you listed. – McGarnagle May 21 '12 at 03:51
  • Dim ds As DataSet,, i declared it in Class Form – Derick Baquilod Operario May 21 '12 at 03:55
  • 2
    Well, you have declared it, (otherwise your code will not compile) but, ds need to be initialized somewhere and filled with tables. Do you have `ds = New DataSet()` and `daAdapter.Fill(ds)` or do you have added manually tables to this dataset? You can't use ds without the first code and you can't use tables inside the dataset without the second code. – Steve May 21 '12 at 07:48
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Enigmativity Dec 26 '18 at 07:37

1 Answers1

0

Put a break-point (F9 or click in the margin) on this line of code: maxrows = ds.Tables("asdf").Rows.Count and run it.

Take these steps:

  • Hover over ds or right-click and select Quick Watch and see if it says null.
  • If it doesn't, highlight ds.Tables("asdf") and Quick Watch it and see if it's null.
  • If not, then highlight ds.Tables("asdf").Rows and see if that's null.

One of these has to be null if it's crashing there. If that's the case, then you didn't fill it correctly or there wasn't nothing to fill it with.

Yatrix
  • 13,361
  • 16
  • 48
  • 78