![](/img/trans.png)
[英]How to save data from datagridview to sql database without using a button
[英]How to save newly added data in a row or rows from DataGridView into SQL Server when the user clicks a button
如果能為我修改以下代碼,以便將數據從DataGridView逐行保存到SQl Server中,將不勝感激。 當前,該代碼可以一次保存所有行中的數據,而不是在用戶單擊按鈕時僅保存一行或多行中最近添加的數據。
Dim cmd As New SqlCommand
Try
Dim i As Integer
For i = 0 To dgMarksEntry.Rows.Count - 1
If dgMarksEntry.Item(1, i).Value = "" Then
Else
qry = "insert into StudentDetails.MarksEntry values ('" & dgMarksEntry.Item(0, i).Value & "', '" & dgMarksEntry.Item(2, i).Value & "','" & dgMarksEntry.Item(3, i).Value & "','" & dgMarksEntry.Item(4, i).Value & "') "
cmd = New SqlCommand(qry, cn)
cmd.ExecuteNonQuery()
End If
Next
Catch ex As Exception
MessageBox.Show("Insert Error: " & ex.Message)
Finally
End Try
MessageBox.Show("Record successfully saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
我將在單獨的事件(例如rowsadded事件)中跟蹤行索引。 然后在循環中,僅在“ i”與您跟蹤的行索引匹配時才執行sql命令。 然后,在循環結束后清除數組(或使用的任何方法)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.