Utilizo un datagridview con propiedad SelectionMode en FullRowSelect, uso el evento cellclick para rellenar textbox de datos pero al seleccionar una fila que contenga datos nulos devuelve el siguiente error: System.InvalidCastException: 'La conversión del tipo 'DBNull' en el tipo 'String' no es válida.'
Este es mi codigo del evento CellClick
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim dgv As DataGridView = TryCast(sender, DataGridView)
If dgv IsNot Nothing AndAlso dgv.SelectedCells.Count > 0 Then
Dim cell As DataGridViewCell = dgv.SelectedCells(0)
If row IsNot Nothing Then
txtcodigo.Text = DataGridView1.SelectedCells.Item(0).Value
txtdescrip.Text = DataGridView1.SelectedCells.Item(1).Value
txtubic.Text = DataGridView1.SelectedCells.Item(2).Value
txtp1.Text = DataGridView1.SelectedCells.Item(3).Value
txtp2.Text = DataGridView1.SelectedCells.Item(4).Value
txtp3.Text = DataGridView1.SelectedCells.Item(5).Value
txtpdiv1.Text = DataGridView1.SelectedCells.Item(6).Value
txtpdiv2.Text = DataGridView1.SelectedCells.Item(7).Value
txtpdiv3.Text = DataGridView1.SelectedCells.Item(8).Value
End If
End If
End Sub
Cabe destacar que me guie por el codigo muy similar que uso para el evento Selection changed, en el cual no tengo ningun tipo de errores:
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
Dim dgv As DataGridView = TryCast(sender, DataGridView)
If dgv IsNot Nothing AndAlso dgv.SelectedRows.Count > 0 Then
Dim row As DataGridViewRow = dgv.SelectedRows(0)
If row IsNot Nothing Then
txtcodigo.Text = row.Cells(0).Value.ToString()
txtdescrip.Text = row.Cells(1).Value.ToString()
txtubic.Text = row.Cells(2).Value.ToString()
txtp1.Text = row.Cells(3).Value.ToString()
txtp2.Text = row.Cells(4).Value.ToString()
txtp3.Text = row.Cells(5).Value.ToString()
txtpdiv1.Text = row.Cells(6).Value.ToString()
txtpdiv2.Text = row.Cells(7).Value.ToString()
txtpdiv3.Text = row.Cells(8).Value.ToString()
End If
End If
End Sub