1

I have a datagridview and it contain 5 rows, the column name are: XS,S,M,L, and XL.

And the flow is first The user will choose a brand(CHL and XRA), and if the user choose the XRA, the column names will be rename to -,1L,2L,3L,4L.

What the problem here is that every time I get the value from the cell that the column name is renamed, I'm getting this kind of error: Object reference not set to an instance of an object.

This is my sample code for getting the value from the cell:

dvJOBranch.Rows(0).Cells.Item("M").Value.ToString

This code is perfectly working if do not rename the column, but if I rename the column, its having an error.

Chris
  • 7,989
  • 10
  • 30
  • 48
Matthew
  • 620
  • 2
  • 15
  • 37

2 Answers2

1

If the index of the column does not change, you could access it by its index instead of its name:

dvJOBranch.Rows(0).Cells.Item(2).Value.ToString 'third column

Note that Object reference not set to an instance of an object means you have a NullReferenceException

The line of code above supposes that:

  • dvJOBranch.Rows(0) is not null, otherwise access to Cell will throw a NullReferenceException
  • dvJOBranch.Rows(0).Cells.Item(2) is not null, otherwise access to Item(2).Value will throw a NullReferenceException
  • dvJOBranch.Rows(0).Cells.Item(2).Value is not null, otherwise call of .ToString() method will throw a NullReferenceException

You need to make appropriate tests to handle null values.

If dvJOBranch.Rows(0).Cells.Item(2).Value IsNot Nothing Then
    (...)
End If

See also What is a NullReferenceException, and how do I fix it?

Community
  • 1
  • 1
Chris
  • 7,989
  • 10
  • 30
  • 48
0

Try the following:

If dvJOBranch.Rows(0).Cells.Item(2).Value IsNot Nothing OrElse String.IsNullOrEmpty(dvJOBranch.Rows(0).Cells.Item(2).Value.ToString)
(...)
End if

The most important here is the OrElse (in stead of OR), because otherwise the second part of the equasion still gives the NullReferenceException.

Grecht
  • 31
  • 1
  • 10