运行微软提供的例子 如何:将数据绑定到 Windows 窗体 DataGridView 控件
Private Sub GetData(ByVal selectCommand As String)
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" + _
"Initial Catalog=Northwind;Data Source=localhost"
' Create a new data adapter based on the specified query.
Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString)
' Create a command builder to generate SQL update, insert, and
' delete commands based on selectCommand. These are used to
' update the database.
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
' Populate a new data table and bind it to the BindingSource.
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
' Resize the DataGridView columns to fit the newly loaded content.
Me.dataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try
End Sub
提交更改
' Update the database with the user's changes.
Me.dataAdapter.Update(CType(Me.bindingSource1.DataSource, DataTable))
问题出现 当执行添加添加保存时正确;执行修改修改保存正确;但执行添加修改后报“违反并发性: UpdateCommand 影响了预期1条记录中的0条”,
问题产生的原因是数据库里数据修改了,但内存的数据未修改,导致数据库内存的数据不一致。
解决: 在update后添加 代码 Ds.AcceptChanges() 即可