0

I am having trouble connecting my mdb database. I am trying to add some data from form into the database but as i run the application and click on add button, it shows following error:- "System.NullReferenceException: 'Object reference not set to an instance of an object.'" "cmd was nothing". This is my code :-

Public Class addForm
Dim cnn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Private Sub addForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

    Try
        cnn = New OleDb.OleDbConnection
        cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\krish\source\repos\DDC Library Management System\DDC Library Management System\bin\Debug\data.accdb"
        cmd.Connection = cnn
        cnn.Open()
        cmd.CommandText = "INSERT INTO Books(BookType,BookCode,BookName,Publication,Price,Author,dt)VALUES(@bookType, @bookCode, @bookName, @publication, @price, @author, @dt)"
        cmd.Parameters.AddWithValue("@bookType", bookType.SelectedItem)
        cmd.Parameters.AddWithValue("@bookCode", bookCode.Text)
        cmd.Parameters.AddWithValue("@bookName", bookName.Text)
        cmd.Parameters.AddWithValue("@publication", txtPublication.Text)
        cmd.Parameters.AddWithValue("@price", txtPrice.Text)
        cmd.Parameters.AddWithValue("@author", txtAuthor.Text)
        cmd.Parameters.AddWithValue("@dt", dtDate.Value)
        cmd.ExecuteNonQuery()
        cnn.Close()
        MessageBox.Show("Data Added")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub End Class

'addForm' is the name of my current form.

This is the error it is showing as soon as i click on ADD Button

  • Where do you assign an object to `cmd`? – jmcilhinney Sep 07 '20 at 10:40
  • You are trying to use a Null object when you call the object "cmd". Add this line after Try directly to create the object first `cmd = New OleDb.OleDbCommand` – mamadsp Sep 07 '20 at 10:58
  • You can get Visual Studio to write all this code for you, by the way.. – Caius Jard Sep 07 '20 at 16:56
  • @CaiusJard How so? How can i get visual studio to write all this code? Please tell me, it will help a lot – Krishna Saxena Sep 10 '20 at 17:11
  • @KrishnaSaxena for example https://youtu.be/zrtjZlTYLQA - there is a lot more than can be covered in 9 minutes, but if you were to do that process in the video, then VS would have written all the code like above and more.. – Caius Jard Sep 10 '20 at 18:38

0 Answers0