C# Foreach 循环 - 继续问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/815134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Foreach Loop - Continue Issue
提问by Goober
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());
}
}
采纳答案by Jon Skeet
Well, you're currently checking whether the cell's sizeis 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 valueof 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;
}
回答by Rik
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 sizeof the cell is empty. Is this really what you want to do?
此外,您正在检查单元格的大小是否为空。这真的是你想做的吗?
What errors are you getting?
你有什么错误?
回答by Pat
Shouldn't you be checking if the cell's value is empty not the size?
您不应该检查单元格的值是否为空而不是大小吗?
if(String.IsNullOrEmpty(cell.Value.ToString()))
continue;
回答by harish
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());
}
}