Reputation: 163
I'm getting this error and I don't know how to fix it. I know i'm supposed to write what I've tried, but i have no idea what to try, even after looking for a few hours about how to deal with the error.
If more information is needed please let me know. Thanks
The highlighted part of the code is:
Dim cdtrabajador As String = dgvr.Cells(0).Value.ToString
Object reference not set to an instance of an object.
NullReference Exception was unhandled by user code
Private Sub PeopleDataGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
If DataGridView1.RowCount > 0 AndAlso e.RowIndex > -1 Then
If e.RowIndex > -1 Then
Dim dgvr As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
Dim cdtrabajador As String = dgvr.Cells(0).Value.ToString
Dim qry = From dr As PersonalObraDataSet.PersonalObRow In PersonalObraDataSet.PersonalOb Where dr.cdTrabajador = cdtrabajador
If qry.Count > 0 Then
Dim Nombre As String = qry.First.Nombre1
dgvr.Cells(1).Value = Nombre
End If
End If
End If
End Sub
Upvotes: 0
Views: 25938
Reputation: 26068
Hard to say for sure what the root of the issue is, but you may be safe to just null check the cell before you attempt to perform any action on it, and return in the case where the cell is null. Something like:
Dim cellObj as Object = dgvr.Cells(0).Value
if Not cellObj = Nothing Then
Dim cdtrabajador As String = cellObj.ToString
'...
'Perform the rest of your code
Else
Return
Also note that if Cells(0)
is actually null, invoking Value
on it may also be causing the error. If you use your debugger you should be able to pinpoint which value is null and either handle it, or look into reasons why it is null if you expect a value to be present and it isn't.
Upvotes: 3