简体   繁体   中英

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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