Hi,
I'd like to get the value of a column from a datagrid and insert that to a table. I get an error "Object reference not set to an instance of an object."
Here's my code:
Imports System.Data.SqlClient
Imports System.Data
Public Class Class1
Public Shared Sub insertrecord(ByVal query As String)
con.Open()
com.Connection = con
com.CommandText = query
com.ExecuteNonQuery()
con.Close()
End Sub
Public Shared Sub readrecord(ByVal query As String)
con.Open()
com.CommandText = query
com.Connection = con
dr = com.ExecuteReader
End Sub
End Class
Public Class FormRentals
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
Dim indx As Integer = DataGridView1.Rows.Add()
DataGridView1.Rows(indx).Cells(0).Value = (indx + 1).ToString
DataGridView1.Rows(indx).Cells(1).Value = txtboxName.Text
DataGridView1.Rows(indx).Cells(2).Value = FormatNumber(txtboxamt.Text,2).ToString
End Sub
Private Sub btnaddtocart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaddtocart.Click
'This generates a primary key called ID that is set to be identity(1,1)
Class1.insertrecord("Insert into myTable(Name) values('" + txtboxName.Text + "')")
For x As Integer = 0 To (DataGridView1.Rows.Count() - 1)
Class1.readrecord("Select * from myTable where Name='" + DataGridView1.Rows(x).Cells(1).Value.ToString + "'")
If Class1.dr.Read() then
Dim myID as Integer = Class1.dr("ID")
Class1.con.Close
Class1.insertrecord("Insert into amtdue(nameID,name,amount) values('" + myID.ToString + "','" + DataGridView1.Rows(x).Cells(1).Value.ToString + "','" + CType(DataGridView1.Rows(x).Cells(2).Value,Double).ToString + "')")
End if
Class1.con.Close
End Sub
End Class
The thing is -- when I look at table amtdue, everything is actually saved there. I just don't understand why I'm getting the error, and so I can't proceed with what I have to do after clicking the btnaddtocart button.
Would really appreciate any help. Thanks much in advance!