views:

4228

answers:

5

I have a datagridview that is populated with 4 columns and multiple rows of data. I want to iterate through the datagridview and get the cell value from A SPECIFIC COLUMN ONLY, since i need this data to pass into a method.

Here is my code:

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

        GetQuestions(cell.Value.ToString());

    }
}

This just seems to go through all the cells however i need to be able to specify something like:

foreach (DataGridViewRow row in this.dataGridView2.Rows)
{                            
    foreach (DataGridViewCell cell in row.Cells[2])//Note specified column index
    {
        if (cell.Value == null || cell.Value.Equals(""))
        {
            continue;
        }
        GetQuestions(cell.Value.ToString());
    }
}
+1  A: 

Don't you just want to remove the inner foreach loop? Or have I missed something?

foreach (DataGridViewRow row in this.dataGridView2.Rows)
{                            
    DataGridViewCell cell = row.Cells[2]; //Note specified column index
    if (cell.Value == null || cell.Value.Equals(""))
    {
        continue;
    }

    GetQuestions(cell.Value.ToString());
}
Tim Robinson
Thankyou, been up coding for too long, it seems...... :-D
Goober
It's the middle of the morning in my time zone, so you might need to return the favour in 12 hours time ;)
Tim Robinson
haha, i'm in England which is where i presume you are too.....
Goober
A: 

Perhaps you could check the ColumnIndex? Would still loop through all the cells though.

if (cell.Value == null || cell.Value.Equals("") || cell.ColumnIndex != 2)
{
    continue;
}
Sam
+1  A: 
foreach (DataGridViewRow row in this.dataGridView2.Rows)
        {
            DataGridViewCell cell = row.Cells["foo"];//Note specified column NAME
            {
                if (cell != null && (cell.Value != null || !cell.Value.Equals("")))
                {
                    GetQuestions(cell.Value.ToString());
                }
            }
        }
DaDa
Thank you... I was searching for this piece of Code, though not in the same context...
The King
A: 

How i can introduce manual data in a datagridview

A: 

Thanks the above coding working very well once again thanks a lot

Regards, Karthick.

Karthick Raj