我正在使用vb.net windows窗体,我有一个数据网格视图,我正在尝试保存数据网格值
我将数据保存到两个表...我的表名:
1->CompanyMaster_tbl
2->DepartmentMaster_tbl
我在保存按钮中给出了代码:
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
来到这条线时出现错误:
For CompanyMaster_row As DataRow In CompanyMaster_tbl.Rows
对象引用未设置为对象的实例为什么我收到此错误?我的代码有什么问题
答案 0 :(得分:1)
我不在VB.NET中工作(而是在C#中工作),但你的代码毫无意义。
你说......
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.
所以,它肯定会抛出你的空引用异常。
而不是说...
For Each CompanyMaster_row As DataRow In CompanyMaster_tbl.Rows
为什么不循环遍历gridview中的行,然后填充数据表
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