2016-03-24 50 views
1

我想在VB中的datagridview中替换空值。正在从访问数据库读入数据。每次运行它时,都会收到与“System.NullReferenceException”有关的错误。DataGridView替换空值

Sub dataGridView1_CellFormatting(ByVal sender As Object, _ 
    ByVal e As DataGridViewCellFormattingEventArgs) _ 
    Handles DataGridView1.CellFormatting 

    If e.ColumnIndex = Me.DataGridView1.Columns(7).Index Then _ 
     ' AndAlso (e.Value IsNot Nothing) Then 


     With Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex) 

      If e.Value.Equals("") Then 
       e.Value = "very bad" 
      End If 
     End With 

    End If 

End Sub 

对这个问题的任何帮助将不胜感激!

+0

“”与DBNull不是同一个东西,空字符串也不是DBNull与NRE的原因相同 – Plutonix

+0

请显示您的代码以访问返回您的数据,然后设置到'DataGridView' ...这应该在通话中处理,而不是在cellformatting事件中*** ...... – Codexer

+0

这是你在找什么? 'Private Sub frmViewAll_Load(sender As Object,e As EventArgs)处理MyBase.Load Me.TblStudentsTableAdapter.Fill(Me.StudentRecords1DataSet.tblStudents)' – Donncha

回答

0

您需要检查实际的数据库调用。您可以检查是否有任何字段是Null并将其替换。然后,你不必处理他们的代码......

IIF(ISNULL(yourcolumn),'', yourcolumn) 

这将检查如果列null如果是用空字符串替换它,否则将返回值...

0

尝试IsDBNull

Dim abc As Integer 

abc= IIf(IsDBNull(DGVInvoice.Rows(max).Cells(3).Value) = True, 0, DGVInvoice.Rows(max).Cells(3).Value) 

DGVInvoice是你的DataGrid和max是你的最大行数。