views:

3377

answers:

4

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());
    }
}
+4  A: 

You don't need to use the continue keyword here, you could just do this:

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?

Rik
+2  A: 

Shouldn't you be checking if the cell's value is empty not the size?

if(String.IsNullOrEmpty(cell.Value.ToString()))
    continue;
Pat
+8  A: 

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;
}
Jon Skeet
Don't we C# programmers generally stay away from continue/goto statements? I understand they have their places in some languages and could be used to get away with some nasty things...but personally I've never needed to use a continue statement for anything like the examples above.
Ralph
No, I find continue and break are fine - although I've never used goto. In particular, I wouldn't want to just invert the condition and put everything in another block - the nesting gets crazy compared with the simplicity of "I don't want to do anything else in this iteration if this condition is met."
Jon Skeet
A: 

i want to read only cell[1] data...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());
}

}

harish