0
votes

When I add a new row to a datagridview, I am able to add data to a cell, but when I go to the row with the mouse the data disappears out of the cell. What code is needed to get the data to stay?

Private Sub BindingNavigatorAddNewItem_Click(sender As System.Object, e As System.EventArgs) Handles BindingNavigatorAddNewItem.Click

    ' When a new row is entered add Site id.
    Dim rRow As Integer = 0
    rRow = dgvEstimator2.NewRowIndex

    '' Set Job Site ID
    If IsDBNull(Me.dgvEstimator2(1, rRow).Value) Or IsNothing(Me.dgvEstimator2(1,       rRow).Value) Then
        Me.dgvEstimator2(1, rRow).Value = rJobsiteID
        ' .Rows(DGVRow).Cells(1).Value = objSheet.Cells(excelRow, 1).value  
        Me.dgvEstimator2.Rows(rRow).Cells(1).Value = rJobsiteID
        ' Me.dgvEstimator2.Rows(rRow).Cells(1).Selected = True
        'dataGridView1.Rows[Rowindex].Selected = true
        Me.dgvEstimator2.Rows(rRow).Selected = True
        ' dgvEstimator2.Rows(rRow).SetValues()
        dgvEstimator2.CommitEdit(DataGridViewDataErrorContexts.Commit)

    End If

end sub

Thanks in advance!

1

1 Answers

1
votes

It isn't entirely clear what you are trying to achieve but it sounds like you want to set some default values for the new row?

You shouldn't need to use a button to do this - the new row should show at the bottom of your grid when you have AllowUsersToAddRows set true. There is an event raised when a new row needs default values and there you can populate the cells are you like.

Private Sub dataGridView1_DefaultValuesNeeded(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _
Handles DataGridView1.DefaultValuesNeeded

    Dim index As Integer
    index = DataGridView1.NewRowIndex + 1

    e.Row.Cells("Column1").Value = index.ToString()

End Sub

The cells will still be editable - you can change them to be readonly if you want, which could be a good idea for id columns.