请帮助无法解决由于应用程序崩溃而导致问题存在的位置,但数据库中的数据会更新 [英] please help not able to tress where the issue exists as application crashes but data gets updated in database
本文介绍了请帮助无法解决由于应用程序崩溃而导致问题存在的位置,但数据库中的数据会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的团队,
我正在尝试以vb格式从datagridview批量插入sql数据库,数据已按预期成功以正确的格式插入数据库中,但在运行时出现null引用异常.
请帮忙.!我的代码在这里..
Dear Team,
I am trying to do bulk insert from datagridview in vb form to sql database , the data is sucessfully inserted into the database in correct format as expected, but getting a null reference exception at runtime.
Please help.! My code goes here..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each row As DataGridViewRow In Form2.DataGridView1.Rows
If row.State > DataGridViewElementStates.None Then
Dim nItem As String = row.Cells("Col1").Value.ToString()
Dim nQty As String = row.Cells("Col2").Value.ToString()
Dim nMrp As String = row.Cells("Col3").Value.ToString()
Dim nRate As String = row.Cells("Col4").Value.ToString()
Dim nAmount As String = row.Cells("Col5").Value.ToString()
Dim nBillNo As String = Form2.TextBox3.Text
Dim nTransactionDate As String = DateValue(Now)
Dim nTransactionTime As String = TimeValue(Now)
Dim nUserName As String = Form2.TextBox5.Text
Try
Using connection As New SqlClient.SqlConnection("Server=.;UID=user; PWD=pwd")
Using cmd As New SqlClient.SqlCommand("GetTransaction", connection)
With cmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("@nItem", nItem)
.Parameters.AddWithValue("@nQty", nQty)
.Parameters.AddWithValue("@nMrp", nMrp)
.Parameters.AddWithValue("@nRate", nRate)
.Parameters.AddWithValue("@nAmount", nAmount)
.Parameters.AddWithValue("@nBillNo", nBillNo)
.Parameters.AddWithValue("@nTransactionDate", nTransactionDate)
.Parameters.AddWithValue("@nTransactionTime", nTransactionTime)
.Parameters.AddWithValue("@nUserName", nUserName)
.Prepare()
connection.Open()
.ExecuteNonQuery()
End With
End Using
End Using
Catch ex As NullReferenceException
MsgBox(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
推荐答案
原因是,当DataGridView.AllowUserToAddRows
设置为True
(默认情况下设置为True
)时,在DataGridView
的末尾会有一个empty Row
.当使用For Each
循环迭代Rows
集合时,对于每一行,将执行存储过程,并在数据库中更新数据.当到达DataGridView
的最后一个空行时,会抛出NullReference
异常.
如果在For Each
循环之前将DataGridView.AllowUserToAddRows
设置为False
,则可能不会引发上述异常.
The reason is that when theDataGridView.AllowUserToAddRows
is set toTrue
, which is by default set toTrue
, then there will be anempty Row
at the end of theDataGridView
. When theRows
collection is iterated using theFor Each
loop, for each row the the Stored procedure is executed and the data is updated in the database. When the last empty row of theDataGridView
is reachedNullReference
exception is thrown.
IfDataGridView.AllowUserToAddRows
is set toFalse
before theFor Each
loop, the above exception may not be thrown.
这篇关于请帮助无法解决由于应用程序崩溃而导致问题存在的位置,但数据库中的数据会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文