vb修改DATAGridview表格修改数据后通过按钮保存到数据库的代码
时间: 2023-04-03 11:04:40 浏览: 116
DataGridView修改后直接保存到数据库实例程序
5星 · 资源好评率100%
以下是 VB 代码示例,用于将 DataGridView 中的修改保存到数据库:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connStr As String = "Data Source=yourDataSource;Initial Catalog=yourDatabase;Integrated Security=True"
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
conn.Open()
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow AndAlso row.Cells("id").Value IsNot Nothing Then
cmd.CommandText = "UPDATE yourTable SET column1=@column1, column2=@column2 WHERE id=@id"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("@column1", row.Cells("column1").Value)
cmd.Parameters.AddWithValue("@column2", row.Cells("column2").Value)
cmd.Parameters.AddWithValue("@id", row.Cells("id").Value)
cmd.ExecuteNonQuery()
End If
Next
conn.Close()
MessageBox.Show("保存成功!")
End Sub
请注意,您需要将代码中的“yourDataSource”、“yourDatabase”、“yourTable”、“column1”、“column2”和“id”替换为您自己的数据库信息和表格列名。
阅读全文