VB.Net - “用户代码未处理 NullReferenceException”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18682042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.Net - "NullReferenceException was unhandled by user code"
提问by Jeffrey Lopez
Here is the code in my DataGridView's SelectionChanged event:
这是我的 DataGridView 的 SelectionChanged 事件中的代码:
Dim a as Integer
a = DataGridView1.CurrentRow.Index 'this certain line contains the error
TextBox1.Text = DataGridView1.Item(0,a).Value
'and all that jazz
The code runs, but when a cell is clicked followed by any column header, the error shows up.
代码运行,但是当单击单元格后跟任何列标题时,错误就会显示出来。
I tried placing this block of code in another event called CellContentClick but clicking on the cells in the datagridview is not that responsive as compared to SelectionChanged.
我尝试将此代码块放置在另一个名为 CellContentClick 的事件中,但与 SelectionChanged 相比,单击 datagridview 中的单元格的响应速度不那么快。
Any ideas on how to fix this?
有想法该怎么解决这个吗?
回答by aleroot
The DataGridView or the DataGridView1.CurrentRow are null ...
DataGridView 或 DataGridView1.CurrentRow 为 null ...
To avoid the error you can simply ensure that they are not null before attempting to access them :
为了避免错误,您可以在尝试访问它们之前简单地确保它们不为空:
Dim a as Integer = 0
If DataGridView1 IsNot Nothing AndAlso DataGridView1.CurrentRow IsNot Nothing Then
a = DataGridView1.CurrentRow.Index 'this certain line contains the error
EndIf
回答by ajr
OK - I know this is an old post, but I read the above and came up with this code, so I thought I would share it.
好的 - 我知道这是一篇旧帖子,但我阅读了上面的内容并想出了这段代码,所以我想我会分享它。
Private Function TryReturnString(ByRef obj As Object) As String
Dim rtn As String = String.Empty
If obj IsNot Nothing Then
rtn = obj.ToString
End If
Return rtn
End Function
Or for the above:
或者对于上述:
Private Function TryReturnIndex(ByRef curRow As DataGridViewRow) As Integer
Dim rtn As Integer = 0
If curRow IsNot Nothing Then
rtn = curRow.Index
End If
Return rtn
End Function

