VB.NET对象引用未设置为对象的实例

时间:2013-02-09 17:04:12

标签: datagridview vb.net-2010

在将数据传输到新项目并将项目连接到其他服务器之前,我一直在使用以下代码更改datagridview中的单元格值颜色而没有任何问题。它现在抛出一个“对象引用未设置为对象的实例”错误..我错过了什么?

它可以从GridViewTextBoxColumn1开始工作,直到它向下移动到GridViewTextBoxColumn2并且调试器开始抛出错误。值无法转换为类型Datetime,然后没有设置对象引用等。但我检查到处都是,一切似乎都到位,并且不明白它是如何结束日期时间的。

 Private Sub TableGrid_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles TableGrid.CellFormatting

    For i As Integer = Nothing To Me.TableGrid.Rows.Count - 1
        If Me.TableGrid.Rows(i).Cells("GridViewTextBoxColumn1").Value <= 0 Then
            Me.TableGrid.Rows(i).Cells("GridViewTextBoxColumn1").Style.ForeColor = Color.Red
        End If
    Next
    For j As Integer = Nothing To Me.TableGrid.Rows.Count - 1
        If Me.TableGrid.Rows(j).Cells("GridViewTextBoxColumn2").Value.ToString = "S" Then
            Me.TableGrid.Rows(j).Cells("GridViewTextBoxColumn2").Style.ForeColor = Color.Blue
        End If
    Next

    For k As Integer = Nothing To Me.TableGrid.Rows.Count - 1
        If Me.TableGrid.Rows(k).Cells("GridViewTextBoxColumn3").Value.ToString = "Z" Then
            Me.TableGrid.Rows(k).Cells("GridViewTextBoxColumn3").Style.ForeColor = Color.Blue
        End If
    Next

End Sub

3 个答案:

答案 0 :(得分:0)

找到一个适用于我自己的问题的解决方案..但我相信应该有更好的答案。

我的第一个问题中的代码没有测试某些单元格中存在的空值。因此,错误..

For i As Integer = 0 To Me.TableGrid.Rows.Count - 1
If Not Me.TableGrid.Rows(i).Cells("DataGridViewTextBoxColumn1").Value Is DBNull.Value Then
If Me.TableGrid.Rows(i).Cells("DataGridViewTextBoxColumn1").Value = "Z" Then
Me.TableGrid.Rows(i).Cells("DataGridViewTextBoxColumn1").Style.ForeColor = Color.Blue
End If
End If

        If Not Me.TableGrid.Rows(i).Cells("DataGridViewTextBoxColumn2").Value Is DBNull.Value Then
            If Me.TableGrid.Rows(i).Cells("DataGridViewTextBoxColumn2").Value <0 Then
                Me.TableGrid.Rows(i).Cells("DataGridViewTextBoxColumn2").Style.ForeColor = Color.Red
            End If
        End If

答案 1 :(得分:0)

通常在尝试引用尚未分配任何内容的对象时会发生此错误,因此请确保您的datagrid单元格中实际包含值。

答案 2 :(得分:0)

尝试“Dim yourobject As New Yourtype”,因为抛出此异常时通常需要“New”,