C#检查datagridview列是否为空

时间:2012-06-15 09:02:12

标签: c# datagridview

我想检查datagridview中的“many”列是否为空。

这里是我的代码

        for (int i = 0; i < (gridx.Rows.Count - 1); i++)
        {
            col = gridx.Rows[i].Cells["code"].Value.ToString();
            col4 = gridx.Rows[i].Cells["many"].Value.ToString();                
        }

        if (col4 == "")
        {
            MessageBox.Show("Many is empty");
            this.Focus();
            return;
        } 
        else
        {
          //my code in here
        }

但它没有显示错误“很多是空的”

请帮助我...并在此之前致谢

3 个答案:

答案 0 :(得分:5)

由于您要在for循环中将最后一个单元格值分配给col4,因此可以将其与null进行对齐。

for (int i = 0; i < (gridx.Rows.Count - 1); i++)
        {
            col = gridx.Rows[i].Cells["code"].Value.ToString();
            if(gridxRows[i].Cells["many"].Value == null ||       
               gridxRows[i].Cells["many"].Value == string.Empty)
             {
                col4 = gridx.Rows[i].Cells["many"].Value.ToString();
             }
         }

您当前的代码只会检查cell["many"]的最后一行是否为空。如果您想确保所有列都是空的,那么您可以尝试以下方法。

bool isColumnEmpty = true;
for (int i = 0; i < (gridx.Rows.Count - 1); i++)
        {
            col = gridx.Rows[i].Cells["code"].Value.ToString();
            if(gridxRows[i].Cells["many"].Value == null ||       
               gridxRows[i].Cells["many"].Value == string.Empty)
             {
                col4 = gridx.Rows[i].Cells["many"].Value.ToString();
                isColumnEmpty = false; // that means some thing is found against cell
             }
         }

现在检查是否设置了isColumnEmpty标志;

if(isCoulmnEmpty)
{
            MessageBox.Show("Many is empty");
            this.Focus();
            return;
}

答案 1 :(得分:1)

试试这个。

if(gridx.Rows[i].Cells["code"].Value == null)
{
// do something here...
}

此致 Sharmila

答案 2 :(得分:0)

如果您使用databinding填充datagrid,我建议您“询问”您搜索的值(或更好的缺席值)的数据。

如果你在UI上搜索,在这个的情况下,根据你的帖子,如果永远不会运行,我会看到2个选项:

  • 某个值,所以它不是空的
  • 或值不是""(空字符串),而是null。要检查这一点,就这样编写就足够了:

if (col4 == null)

只是建议:使用Visual Studio的强大调试工具,并在几分钟内自己找出答案。

祝你好运。

相关问题