我需要将Datagridview的数据插入MS Access数据库。当我在datagridview的所有单元格中写入数据时,一切都很好。但有时我只需要在3列6中编写数据!
我收到错误:
对象引用未设置为对象的实例。
这是我试过的代码:
Dim billsql As String = "insert into tblbill(inum, idate,cname,caddress,cphone,datein,timein,dateout,timeout,carname,carmodel,carid, " _
& "iamount, irepairs, itechnical, samount, sname, snum, itotal, stotal, idisscount, inet, isign, csign) " _
& "values(@inum, @idate, @cname,@caddress,@cphone,@datein,@timein,@dateout,@timeout,@carname,@carmodel,@carid, " _
& "@iamount, @irepairs, @itechnical, @samount, @sname, @snum, @itotal, @stotal, @idisscount, @inet, @isign, @csign)"
Try
For i = 0 To dgv.Rows.Count - 1
For j = 0 To dgv.Columns.Count - 1
If dgv.Rows(i).Cells(j).Value IsNot Nothing Then
Using billconn As OleDbConnection = New OleDbConnection(constr)
Using billcmd As New OleDbCommand
billcmd.Connection = billconn
billcmd.CommandType = CommandType.Text
billcmd.CommandText = billsql
billcmd.Parameters.AddWithValue("@inum", Val(TextBox4.Text))
billcmd.Parameters.AddWithValue("@idate", dt.Value.Date)
billcmd.Parameters.AddWithValue("@cname", TextBox1.Text)
billcmd.Parameters.AddWithValue("@caddress", TextBox2.Text)
billcmd.Parameters.AddWithValue("@cphone", TextBox3.Text)
billcmd.Parameters.AddWithValue("@datein", dtin.Value.Date)
billcmd.Parameters.AddWithValue("@timein", tmin.Value.ToShortTimeString)
billcmd.Parameters.AddWithValue("@dateout", dtout.Value.Date)
billcmd.Parameters.AddWithValue("@timeout", tmout.Value.ToShortTimeString)
billcmd.Parameters.AddWithValue("@carname", TextBox5.Text)
billcmd.Parameters.AddWithValue("@carmodel", TextBox6.Text)
billcmd.Parameters.AddWithValue("@carid", TextBox7.Text)
billcmd.Parameters.AddWithValue("@iamount", Val(dgv.Rows(i).Cells(0).Value))
billcmd.Parameters.AddWithValue("@irepairs", dgv.Rows(i).Cells(1).Value.ToString)
billcmd.Parameters.AddWithValue("@itechnical", dgv.Rows(i).Cells(2).Value.ToString)
billcmd.Parameters.AddWithValue("@samount", Val(dgv.Rows(i).Cells(3).Value))
billcmd.Parameters.AddWithValue("@sname", dgv.Rows(i).Cells(4).Value.ToString)
billcmd.Parameters.AddWithValue("@snum", dgv.Rows(i).Cells(5).Value.ToString)
billcmd.Parameters.AddWithValue("@itotal", Val(TextBox14.Text))
billcmd.Parameters.AddWithValue("@stotal", Val(TextBox16.Text))
billcmd.Parameters.AddWithValue("@idisscount", Val(TextBox15.Text))
billcmd.Parameters.AddWithValue("@inet", Val(TextBox17.Text))
billcmd.Parameters.AddWithValue("@isign", username)
billcmd.Parameters.AddWithValue("@csign", TextBox1.Text)
billconn.Open()
billcmd.ExecuteNonQuery()
billcmd.Dispose()
billconn.Close()
End Using
End Using
End If
Next j
Next i
MsgBox("Saved Successfully!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "")
End Try