C# Foreach Loop - Continue Issue

Goober picture Goober · May 2, 2009 · Viewed 73.9k times · Source

I have a problem with a continue statement in my C# Foreach loop.

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.

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());
    }
}

Answer

Jon Skeet picture Jon Skeet · May 2, 2009

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;
}