简体   繁体   English

Vb.net编辑DatagridView

[英]Vb.net Editing DatagridView

I created a simple program where I can search through a database table. 我创建了一个简单的程序,可以在其中搜索数据库表。 Add data and remove data through a button. 通过按钮添加数据和删除数据。 Now I want to be able to update the data within the datagrid view however i am getting the classic error: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information. 现在,我希望能够更新datagrid视图中的数据,但是我遇到了经典的错误:不支持不返回任何键列信息的SelectCommand,不支持UpdateCommand的动态SQL生成。

I have the primary key in the data grid that is not attached to anything in the vb.net program nor in the database at this time. 我的主键位于数据网格中,该主键目前未附加到vb.net程序或数据库中的任何内容。 I am not sure what I am missing. 我不确定我缺少什么。

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

Actually I was incorrect. 其实我是不对的。 I did not have a primary key set on my database. 我的数据库上没有设置主键。 I dropped my table - recreated with primary key. 我放下了表格-用主键重新创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM