0

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!

0

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.