[大家好,请帮我一下,我用什么代码将datagridview中的数据保存到我的数据库保存按钮?
非常感谢!] 1
答案 0 :(得分:0)
If dgv.IsCurrentCellInEditMode = True Then
MsgBox("Please exit edit mode and try again.")
Exit Sub
End If
Execute("DELETE FROM tblSample;")
Dim c As Integer = 0
Dim dgv As Integer = dgv.Rows.Count - 1
While c < dgv
Execute("INSERT INTO tblSample VALUES (" + dgv.Item(0, c).Value.ToString + "," + dgv.Item(x, c).Value.ToString + ");")
c += 1
End While
fillDatatable(xDT, "SELECT * FROM tblSample;")
dgv.DataSource = xDT
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
dgv.Refresh()
MsgBox("Changes Applied!")
Public Sub fillDatatable(_datatable As DataTable, Query As String)
Dim sqlQuery As String = (Query)
Using conn As New SqlConnection(yourConnectionString)
conn.Open()
Using da As New SqlDataAdapter(sqlQuery, conn)
da.Fill(_datatable)
End Using
conn.Close()
End Using
End Sub
这假设你有一个&#34;执行&#34;执行SQL查询的方法。 (tblSample =你的桌子) (dgv =您的datagrdview)(x =行号(0,1,2,3 ...))它使用数据表作为临时&#34;保存点&#34;对于数据,不是最有效的,但它应该工作。希望它有所帮助!的xD