2

I'm using a cellformatting even to use the Employee ID Column of a bound datagridview to look up the "Employee ID" in another datatable and return the Employee name on the UNbound "Name" Column.

  Private Sub PartePersonalDataGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If DataGridView1.RowCount > 0 AndAlso e.RowIndex > -1 Then
        Dim dgvr As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
        Dim empID As Integer = CInt(dgvr.Cells(0).Value)
        Dim qry = From dr As PersonalObraDataSet.PersonalObRow In _PersonalObraDataSet.PersonalOb _
                  Where dr.cdTrabajador = empID
        If qry.Count > 0 Then
            DataGridView1.Rows(e.RowIndex).Cells(1).Value = qry.First.Nombre1
            'DataGridView1.Rows(e.RowIndex).Cells(5).Value = qry.First.Nombre2
        End If
    End If
End Sub

Everything load fine and the required name for each ID are loaded fine, but when the the new row is added, the cellformatting event fires before there is a chance to type in the New Employee ID, giving a DBNull error, because the cell it is looking at is empty.

I've looked for a while and i can't find a way to tell the cellformatting to fire after the cell edit is done or on cell leave, or to not format the cell if the field Employee ID is empty.

4

1 回答 1

2

我认为您无法“决定”何时触发 cellFormating 事件。但是,如果我理解您的问题,我认为您需要测试 cell.value 是否为 null

如果 cell.value 为空,这行代码会给你一个错误。

Dim empID As Integer = CInt(dgvr.Cells(0).Value)

所以你需要做这样的事情:

If dgvr.Cells(0).Value IsNot nothing AndAlso dgvr.Cells(0).Value IsNot DbNull.value Then
   Dim empID As Integer = CInt(dgvr.Cells(0).Value)

   (...)

End If
于 2013-07-19T16:47:57.703 回答