Reputation: 640
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.
Upvotes: 1
Views: 1946
Reputation: 31
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.
Upvotes: 0
Reputation: 8647
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?
Upvotes: 1