2016-03-24 84 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是你的最大行數。