您好我使用以下代码在文本框中显示datagridview的选定行数据。我遇到的问题是当用户单击datagrid视图的空行时出现错误。
请帮忙
Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.txtBoxServTypeID.Text = DataGridView1.Item(0, i).Value
Me.txtBoxServiceType.Text = DataGridView1.Item(1, i).Value
Me.txtBoxCapacity.Text = DataGridView1.Item(2, i).Value
End Sub
答案 0 :(得分:0)
在空行上,行索引为-1,因此尝试访问DataGridView1.Item(0, -1).Value
会导致错误
答案 1 :(得分:0)
更新了代码。我目前无法测试它,因为Windows更新导致我的电脑出现冻结问题,所以我可能会有错误。
尝试
Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
If String.IsNullOrEmpty(CStr(DataGridView1.Item(0, i).Value)) orelse String.IsNullOrEmpty(CStr(DataGridView1.Item(1, i).Value)) orelse String.IsNullOrEmpty(CStr(DataGridView1.Item(2, i).Value))Then
Messagebox.Show("Empty row clicked - no data returned")
else
Me.txtBoxServTypeID.Text = DataGridView1.Item(0, i).Value
Me.txtBoxServiceType.Text = DataGridView1.Item(1, i).Value
Me.txtBoxCapacity.Text = DataGridView1.Item(2, i).Value
End If
End Sub
这种方式至少让用户知道他们做错了什么。如果这是您的单击处理程序中的所有代码,那么这可能就足够了,但如果您有其他代码,则可能需要处理If语句返回的数据缺失
答案 2 :(得分:0)
你可以像这样更新你的代码:
Dim i As Integer
i = DataGridView1.CurrentRow.Index
if Not isDBNull(DataGridView1.Item(0, i).value) then
Me.txtBoxServTypeID.Text = DataGridView1.Item(0, i).Value
Me.txtBoxServiceType.Text = DataGridView1.Item(1, i).Value
Me.txtBoxCapacity.Text = DataGridView1.Item(2, i).Value
end if