Vb.net 编辑 DatagridView
Posted
技术标签:
【中文标题】Vb.net 编辑 DatagridView【英文标题】:Vb.net Editing DatagridView 【发布时间】:2015-04-07 15:39:03 【问题描述】:我创建了一个简单的程序,可以在其中搜索数据库表。通过按钮添加数据和删除数据。现在我希望能够更新数据网格视图中的数据,但是我遇到了经典错误:不支持不返回任何键列信息的 SelectCommand 为 UpdateCommand 生成动态 SQL。
我在数据网格中有一个主键,它没有附加到 vb.net 程序中的任何内容,也没有附加到数据库中。我不确定我错过了什么。
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=Inventory;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, First_Name, Last_Name, Item FROM Inventory_Details", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
'Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
DataGridView1.AllowUserToAddRows = True
DataGridView1.AllowUserToDeleteRows = True
DataGridView1.[ReadOnly] = False
adap.InsertCommand = builder.GetInsertCommand()
' adap.UpdateCommand = builder.GetUpdateCommand()
adap.UpdateCommand = builder.GetUpdateCommand
adap.Fill(dt)
InventoryDetailsBindingSource.DataSource = dt
DataGridView1.DataSource = InventoryDetailsBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
InventoryDetailsBindingSource.Filter = String.Format("First_Name Like '%0%'", TextBox1.Text)
Else
InventoryDetailsBindingSource.Filter = String.Empty
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
MessageBox.Show("Saved successfully")
Catch ex As Exception
MessageBox.Show("Error updating database")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
adap.Update(dt)
DataGridView1.[ReadOnly] = True
Button2.Enabled = False
End Sub
End Class
【问题讨论】:
【参考方案1】:其实我错了。我的数据库上没有设置主键。我放弃了我的表 - 用主键重新创建。
【讨论】:
以上是关于Vb.net 编辑 DatagridView的主要内容,如果未能解决你的问题,请参考以下文章
数据网格视图更新,在 vb.net windows 窗体中编辑和删除,使用多个表来填充 datagridview