在对象上应用string.IsNullorEmpty [英] Applying string.IsNullorEmpty over an object

查看:88
本文介绍了在对象上应用string.IsNullorEmpty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

尝试在对象(例如dataGridView单元格)上应用方法string.IsNullorEmpty()时遇到问题.

我的方法验证dataGridView每行的2个单元格,并检查两个单元格是否都被填充.

问题是当我使用下面的代码时...

Hi All,

I am having a problem when I try to apply the method string.IsNullorEmpty() over an object, in my case, a dataGridView Cell.

My method verifies 2 cells of each line of a dataGridView and check if both Cells are filled if one of them is.

The problem is that when I use the code below...

for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column1"].Value.ToString()) && string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column2"].Value.ToString()))
                {
                    MessageBox.Show("Please, enter a valid value for each description.");
                    return;
                }
                if(!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column2"].Value.ToString()) && string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column1"].Value.ToString()))
                {
                    MessageBox.Show("Please, enter a valid description for each value.");
                    return;
                }
            }



我的错误对象引用未设置为对象的实例..

我知道为什么会发生这种情况,但是我无法仅使用



I have the error Object reference not set to an instance of an object..

I know why it happens, but, I can''t verify this cell using only

!string.IsNullOrEmpty(dataGridView1.Rows[i].Cells["Column2"].Value)<br />

来验证此单元格.我必须在 .Value 之后使用.ToString(),但是,当我执行代码时,它无法将 null 值转换为字符串,以使其无法使用方法string.IsNullorEmpty().

我该如何做到这一点而不必出错对象引用未设置为对象的实例.?

谢谢是前进! :)

... I have to use .ToString() after .Value, but, when I execute the code, it can''t convert a null value to a string for it to use the method string.IsNullorEmpty().

How can I make it happens without have to error Object reference not set to an instance of an object.?

Thanks is advance! :)

推荐答案

由于dataGridView1.Rows[i].Cells["Column2"].Value的类型为Object,因此您可以简单地检查是否为null:

Because dataGridView1.Rows[i].Cells["Column2"].Value is of type Object, you can simply check for null:

if(dataGridView1.Rows[i].Cells["Column2"].Value != null)
{
//your code here..
}



一旦知道它不为空,就可以进一步检查它是否为空字符串.



Once you know it''s not null, you can go further and check if it''s an empty string.


这篇关于在对象上应用string.IsNullorEmpty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆