Reputation: 183
i am working on vb.net windows form ,I have a data grid view,,i am trying to save data grid values
I am saving data to Two Tables..my Table Names:
1->CompanyMaster_tbl
2->DepartmentMaster_tbl
I given code in save button like this:
Dim CompanyMaster_tbl As DataTable = Nothing
Dim DepartmentMaster_tbl As DataTable = Nothing
For Each CompanyMaster_row As DataRow In CompanyMaster_tbl.Rows
For i As Integer = 0 To gv.RowCount - 2
If gv.Rows(i).Cells("cmpny").Value <> "" Then
sqlInsertT1 &= "Insert Into CompanyMaster_tbl(CompanyName) Values ('" & gv.Rows(i).Cells("cmpny").Value & "');"
Exetransaction(sqlInsertT1)
End If
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells("cmpny").Value)
Next
For Each DepartmentMaster_row As DataRow In DepartmentMaster_tbl.Select(Ccid)
For j As Integer = 0 To gv.RowCount - 2
sqlInsertT2 &= "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" & gv.Rows(j).Cells("Dpmnt").Value & "','" & gv.Rows(j).Cells("dtphon").Value & "','" & gv.Rows(j).Cells("mail").Value & "'," & Ccid & ");"
Exetransaction(sqlInsertT2)
Next
Next
Next
while coming to this line am getting error:
For Each CompanyMaster_row As DataRow In CompanyMaster_tbl.Rows
Object reference not set to an instance of an object why i am getting this error? what is wrong with my code
Upvotes: 0
Views: 408
Reputation: 77876
I don't work in VB.NET (rather in C#) but your code make no sense.
You saying ...
Dim CompanyMaster_tbl
As DataTable = Nothing <-- (here CompanyMaster_tbl set to null)
For Each CompanyMaster_row As DataRow
In CompanyMaster_tbl.Rows <-- you are trying to referencing it.
So, it will definitely throw you null reference exception.
Instead of saying ...
For Each CompanyMaster_row As DataRow In CompanyMaster_tbl.Rows
Why not loop through rows in your gridview and then populate the datatable
For Each DataGridViewRow gr In gv.Rows
If gr.Cells("cmpny").Value <> "" Then
sqlInsertT1 &= "Insert Into CompanyMaster_tbl(CompanyName)
Values ('" & gr.Cells("cmpny").Value & "');"
Exetransaction(sqlInsertT1)
End If
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName",
gr.Cells("cmpny").Value)
Next
Upvotes: 1