System.NullReferenceException datagridview对象引用未设置为对象的实例. [英] System.NullReferenceException datagridview object reference not set to an instance of an object.
本文介绍了System.NullReferenceException datagridview对象引用未设置为对象的实例.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
dataGridView.Rows[e.RowIndex].Cells["ReturnQty"].Value.ToString()
如果当前单元格值为null,则显示NullReferenceException
错误:
我想做
If the current cell value is null it shows the NullReferenceException
error:
I want to do
if(!String.IsNullOrEmpty(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
{
// do sonmthing
}
推荐答案
尝试类似的方法:
Try something like:
if(MainGridView.Rows.Count >0 && MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] != null)
{
if(!String.IsNullOrEmpty(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
{
// do sonmthind
}
}
而不是使用.tostring()
使用Convert.tostring()来处理空值
你可以这样写
Hi,
instead of using .tostring()
use Convert.tostring() as it handles null values
u can write like
if(Convert.Tostring(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value)){ // do sonmthing}
希望对您有帮助.......
:-O
Hope it helps..........
:-O
除了Sandeep的回答外,我还会在if内添加e.RowIndex >= 0 && e.ColumnIndex >= 0
.
并且IsNullOrEmpty
仅采用string
作为参数,但是Cell.Value
属性的类型为Object
.因此,您不能将其直接传递给IsNullOrEmpty
方法.
试试这样的东西:
In addition to Sandeep''s answer, I would adde.RowIndex >= 0 && e.ColumnIndex >= 0
inside if.
AndIsNullOrEmpty
only takes astring
as parameter, butCell.Value
property is of typeObject
. So you can''t pass it directly to theIsNullOrEmpty
method.
Try th something like this:
if (MainGridView.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
DataGridViewCell cell = MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell != null && !String.IsNullOrEmpty(cell.Value as string))
{
// do something
}
}
这篇关于System.NullReferenceException datagridview对象引用未设置为对象的实例.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文