[英]Getting value in datagridview cell error
I have a datagridview
and it contain 5 rows, the column name are: XS,S,M,L, and XL. 我有一个
datagridview
,它包含5行,列名是:XS,S,M,L和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. 首先,流程是用户选择品牌(CHL和XRA),如果用户选择XRA,则列名将重命名为-,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. 如果不重命名该列,则此代码可以完美地工作,但是如果我重命名该列,则它有错误。
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
请注意, 未将对象引用设置为对象的实例意味着您有一个
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)
不为null ,否则对Cell
访问将引发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)
不为null ,否则对Item(2).Value
访问将抛出NullReferenceException
dvJOBranch.Rows(0).Cells.Item(2).Value
is not null , otherwise call of .ToString()
method will throw a NullReferenceException
dvJOBranch.Rows(0).Cells.Item(2).Value
不为null ,否则调用.ToString()
方法将引发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? 另请参见什么是NullReferenceException,以及如何解决它?
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. 这里最重要的是OrElse(而不是OR),因为否则equasion的第二部分仍然给出NullReferenceException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.