vb.net - winforms - datagridview - 数据填入某些单元格的新行 - 消失

时间:2012-03-10 14:29:04

标签: vb.net datagridview cell

当我向datagridview添加一个新行时,我可以向单元格添加数据,但是当我用鼠标去行时,数据会从单元格中消失。获取数据需要什么代码?

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

结束子

提前致谢!

1 个答案:

答案 0 :(得分:1)

您想要实现的目标尚不完全清楚,但听起来您想为新行设置一些默认值?

您不需要使用按钮来执行此操作 - 当AllowUsersToAddRows设置为true时,新行应显示在网格的底部。当新行需要默认值时会引发一个事件,您可以在那里填充单元格。

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

单元格仍然可以编辑 - 如果需要,可以将它们更改为只读,这对于id列来说可能是个好主意。