Goober Goober - 2 years ago 105
C# Question

Getting text only from a specific column of DataGridView

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

Answer Source

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());
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download