Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

VB.net Add Records to bound DataGridView Mimic Return click

Hi

If I load a bound DataGridView with the right code I can manually add a record at the bottom and when
I click return it will add the record. Is there a way to mimic the Return click using VB.net code?

I tried the following but it did not commit the value. When I clicked in the last row everything dissapeared

       Dim oLastRowIndex As Long = Me.DataGridView1.RowCount - 1
          Me.DataGridView1.Rows(oLastRowIndex).Cells(2).Value = "x"
            Me.DataGridView1.Rows(oLastRowIndex).Cells(3).Value = "y"
            Me.DataGridView1.Rows(oLastRowIndex).Cells(4).Value = "z"
            Me.DataGridView1.Rows(oLastRowIndex).Cells(5).Value = "a"
            System.Threading.Thread.Sleep(10)
            SendKeys.SendWait("{ENTER}")

The following image shows how the code populates the last row. If doing this manually it stays there but with code
once I then click in there it vanishes
I also used the following code to commit the change but didn't help
  Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
        Try
            'This is used to make sure that a change is commited to a cell
            If DataGridView1.IsCurrentCellDirty Then
                DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            End If
        Catch ex As Exception

        End Try
    End Sub

User generated image
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Try following


Dim oLastRowIndex as Integer =  DataGridView1.Rows.Add
Me.DataGridView1.Rows(oLastRowIndex).Cells(2).Value = "x"
Me.DataGridView1.Rows(oLastRowIndex).Cells(3).Value = "y"
Me.DataGridView1.Rows(oLastRowIndex).Cells(4).Value = "z"
Me.DataGridView1.Rows(oLastRowIndex).Cells(5).Value = "a"
Avatar of Murray Brown

ASKER

Hi

I get an error saying that rows cannot be added when the DataGridView is data bound
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Great answer. Like the way you think! Thanks