Search code examples
vb.netdatagridviewenter

When I edit a cell and press ENTER I want to update the database


let's see if anyone can help me.

I want that when I edit a cell in a DataGridView and press the ENTER key I update the database.

I have a button that does this to me, but only after editing it (without pressing ENTER), I press the button and it updates the database.

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' we will create save functions in our module
        Dim row, ID As Integer
        Dim Nombre, Apellidos, DNI, Telefono, Email As String
        ' Declare the variable to get value event click on datagridview
        row = DataGridView1.CurrentRow.Index
        ID = DataGridView1(0, row).Value
        Nombre = DataGridView1(1, row).Value
        Apellidos = DataGridView1(2, row).Value
        DNI = DataGridView1(3, row).Value
        Telefono = DataGridView1(4, row).Value
        Email = DataGridView1(5, row).Value
        ' query to Update data into biodata tables
        Dim UpdateData As String = "UPDATE tbl_biodata SET Nombre='" & Nombre & "',Apellidos='" & Apellidos & "',DNI='" & DNI & "',Telefono='" & Telefono & "',Email='" & Email & "' WHERE ID=" & ID & ""
        ' call function to update data
        RunSQL(UpdateData)
        ' fill new data into datagridview1
        showData()
    End Sub

Solution

  • You can use CellEndEdit event. Just specify your column number. Probably you have to check that all desired cell(used in query) are populated.

    Private Sub DataGridView1_EndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        If e.ColumnIndex = 5 Then 'replace 5 with your column number
            Button2.PerformClick()
        End If
    End Sub
    

    Regards