object not set to a reference

I have a data grid view that changes background color of cell depending on a cell value.    when I try to search or filter the text if I type a item number of something that doesn't exist I am getting a System.nullreferenceexception: 'object reference not set to an instance of an abject. How can I fix this?

Private Sub soview_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles SOView.CellFormatting
 
        'red
        If e.ColumnIndex = SOView.Columns(4).Index Then
            If e.Value.ToString = "1" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
            ElseIf e.Value.ToString = "2" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Blue
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
 
            ElseIf e.Value.ToString = "3" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Green
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
            ElseIf e.Value.ToString = "4" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Purple
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
 
 
 
            Else
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Nothing
            End If
        End If
 
    End Sub
sharris_glascolAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pawan KumarDatabase ExpertCommented:
Please try this -

use IsNullOrEmpty.

Private Sub soview_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles SOView.CellFormatting
 
	if ( (string.IsNullOrEmpty(Convert.ToString(e.ColumnIndex))) 
	AND (string.IsNullOrEmpty(Convert.ToString(SOView.Columns(4).Index))) ) THEN 
 
        'red
        If e.ColumnIndex = SOView.Columns(4).Index Then
            If e.Value.ToString = "1" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
            ElseIf e.Value.ToString = "2" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Blue
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
 
            ElseIf e.Value.ToString = "3" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Green
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
            ElseIf e.Value.ToString = "4" Then
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Purple
                SOView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
 
 
 
            Else
                SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Nothing
            End If
        End If
		
	
	Else
		SOView.Rows(e.RowIndex).DefaultCellStyle.BackColor = Nothing
	End If	
 
    End Sub

Open in new window

1
ste5anSenior DeveloperCommented:
Do you really have string data in your grid? String operations are slow..

e.ColumnIndex is a int and cannot be Nothing. But e.Value is an object, thus requires handling. Also SOView maybe Nothing.

And sure that DefaultCellStyle is the correct property, not simply Style?
0
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
try add:

If e.Value Is Nothing Then Exit Sub

Open in new window


Private Sub soview_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles SOView.CellFormatting
 
If e.Value Is Nothing Then Exit Sub

        'red
        If e.ColumnIndex = SOView.Columns(4).Index Then

...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
You want to ensure that you are not resolving an empty datagrid (cell formatting fires before the grid is databound or filled) and that the row that you are modifying is not a new row.

Proof of concept -

Form1.vb -
Public Class Form1
    ReadOnly people = (From i In Enumerable.Range(0, 20) Select New With {.ID = i, .Name = $"Person{i}", .BirthDate = DateTime.Now.AddMonths(-(9 * i)), .IsWorking = i Mod 2 = 0, .Color = If(i Mod 6 = 0, Nothing, If(i Mod 5 = 0, 5, If(i Mod 4 = 0, 4, If(i Mod 3 = 0, 3, If(i Mod 2 = 0, 2, 1)))))}).ToList()
    Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
        SOView.DataSource = people
    End Sub

    Private Sub OnCellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles SOView.CellFormatting
        If TypeOf sender Is DataGridView Then
            Dim grid = CType(sender, DataGridView)
            If grid.Rows.Count > 0 Then
                If Not grid.Rows(e.RowIndex).IsNewRow AndAlso e.ColumnIndex = grid.Columns(4).Index Then
                    Dim [option] As Integer = If(e.Value IsNot Nothing AndAlso Integer.TryParse(e.Value, [option]), [option], 0)
                    grid.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
                    Select Case [option]
                        Case 1
                            grid.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red
                        Case 2
                            grid.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Blue
                        Case 3
                            grid.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Green
                        Case 4
                            grid.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Purple
                        Case Else
                            grid.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.White
                            grid.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Black
                    End Select
                End If
            End If
        End If
    End Sub
End Class

Open in new window


Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.SOView = New System.Windows.Forms.DataGridView()
        CType(Me.SOView, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'SOView
        '
        Me.SOView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
        Me.SOView.Dock = System.Windows.Forms.DockStyle.Fill
        Me.SOView.Location = New System.Drawing.Point(0, 0)
        Me.SOView.Name = "SOView"
        Me.SOView.Size = New System.Drawing.Size(771, 394)
        Me.SOView.TabIndex = 0
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(771, 394)
        Me.Controls.Add(Me.SOView)
        Me.Name = "Form1"
        Me.Text = "Form1"
        CType(Me.SOView, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub

    Friend WithEvents SOView As DataGridView
End Class

Open in new window


Produces the following output -Capture.PNG
-saige-
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.