简体   繁体   English

C#Foreach循环 - 继续问题

[英]C# Foreach Loop - Continue Issue

I have a problem with a continue statement in my C# Foreach loop. 我的C#Foreach循环中的continue语句有问题。

I want it to check if there is a blank cell in the datagridview, and if so, then skip printing the value out and carry on to check the next cell. 我希望它检查datagridview中是否有空单元格,如果是,则跳过打印值并继续检查下一个单元格。

Help appreciated greatly. 非常感谢。

Here is the code: 这是代码:

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

Well, you're currently checking whether the cell's size is zero. 那么,您目前正在检查单元格的大小是否为零。 In a grid, every cell in a column has the same width and every cell in a row has the same height (typically, anyway). 在网格中,列中的每个单元格具有相同的宽度,并且行中的每个单元格具有相同的高度(通常,无论如何)。

You want to be checking based on the value of the cell. 您希望根据单元格的进行检查。 For example: 例如:

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

Tweak this for any other representations of "empty" values that you're interested in. If there are lots, you might want to write a specific method for this, and call it in the check: 对你感兴趣的“空”值的任何其他表示进行调整。如果有很多,你可能想为此编写一个特定的方法,并在检查中调用它:

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

You don't need to use the continue keyword here, you could just do this: 你不需要在这里使用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
    }
}

Also, you're checking whether the size of the cell is empty. 此外,您正在检查单元格的大小是否为空。 Is this really what you want to do? 这真的是你想要做的吗?

What errors are you getting? 你得到了什么错误?

Shouldn't you be checking if the cell's value is empty not the size? 你不应该检查单元格的值是否为空而不是大小?

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

i want to read only cell[1] data...olny 我想只阅读单元格[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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM