我正在使用vb.net windows表单应用程序,我有一个数据网格
我有两个表1->CompanyMaster_tbl
,其中有两个字段。 Cid and CompanyName
,
Cid是此表的主键
2-> DepartmentMaster_tbl
这个有4个字段。 dtid,dtname,dtphon,dtmail,Cid
。
dtid是主键,Cid是外键
单击保存按钮时我想保存两个表中的数据。 在一家公司,我想保存多个部门。我的 Cid 和 dtid 是自动注释,我的意思是身份证明我设置为true ..在保存按钮我给出了这样的代码,
Dim sqlInsertT1 As String = ""
Dim sqlInsertT2 As String = ""
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 :(得分:2)
在您发布的代码中,您在尝试访问之前已将Nothing
的值指定为CompanyMaster_tbl
。这就是你获得例外的原因。
Dim CompanyMaster_tbl As DataTable = Nothing
For Each CompanyMaster_row As DataRow In CompanyMaster_tbl.Rows
当您尝试访问null对象的Rows
属性时,抛出异常。