我的C#Foreach循环中的continue语句出现问题。

我希望它检查datagridview中是否有空白单元格,如果是,则跳过打印该值并继续检查下一个单元格。

非常感谢。

以下是代码:

foreach (DataGridViewRow row in this.dataGridView1.Rows)
{                            
    foreach (DataGridViewCell cell in row.Cells)
    {
        if (cell.Size.IsEmpty)
        {
            continue;
        }
        MessageBox.Show(cell.Value.ToString());
    }
}
有帮助吗?

解决方案

好吧,您当前正在检查单元格的大小是否为零。在网格中,列中的每个单元格具有相同的宽度,并且行中的每个单元格具有相同的高度(通常,无论如何)。

您希望根据单元格的进行检查。例如:

if (cell.Value == null || cell.Value.Equals(""))
{
    continue;
}

对“空”的任何其他表示进行调整。你感兴趣的价值。如果有很多,你可能想为此写一个特定的方法,并在支票中调用它:

if (IsEmptyValue(cell.Value))
{
    continue;
}

其他提示

您不需要在此处使用continue关键字,您可以这样做:

foreach (DataGridViewRow row in this.dataGridView1.Rows)
{                            
    foreach (DataGridViewCell cell in row.Cells)
    {
        if (!cell.Size.IsEmpty) MessageBox.Show(cell.Value.ToString()); // note the ! operator
    }
}

另外,您正在检查单元格的 size 是否为空。这真的是你想要做的吗?

你得到了什么错误?

你不应该检查单元格的值是否为空而不是大小?

if(String.IsNullOrEmpty(cell.Value.ToString()))
    continue;

我想只阅读单元格[1]数据... olny

foreach (DataGridViewRow row in this.dataGridView1.Rows)
{                            
    foreach (DataGridViewCell cell in row.Cells[1])
    {
       if (cell[1].Value == null || cell.Value.Equals(""))
{
    continue;
}

        MessageBox.Show(cell[1].Value.ToString());
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top