【问题标题】:C# check if datagridview column is empty [closed]C#检查datagridview列是否为空[关闭]
【发布时间】:2012-06-15 09:02:11
【问题描述】:

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

这是我的代码

        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
        }

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

请帮帮我.. 之前谢谢

【问题讨论】:

  • 单步调试时'col4'的值是多少?
  • 您想知道一个单元格是空的还是所有单元格?有没有异常,你用过调试器吗?

标签: c# datagridview


【解决方案1】:

由于您在 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;
}

【讨论】:

  • String.Empty 为我工作!谢谢! selectedRow.Cells["Name_Of_Column"].Value.ToString() == String.Empty
【解决方案2】:

试试这个。

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

问候, 沙米拉

【讨论】:

    【解决方案3】:

    如果您使用databinding 填充datagrid,我建议您“询问”有关您搜索的值的数据(或者最好不提供这些数据)。

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

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

    if (col4 == null)

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

    祝你好运。

    【讨论】:

      猜你喜欢
      • 2010-11-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 2018-01-10
      • 1970-01-01
      相关资源
      最近更新 更多