Retrieving text only from a specific DataGridView column

I have a DataGridView that is filled with 4 columns and several rows of data. I want to iterate through a DataGridView and get the cell value only from a specific column, since I need this data to be passed to the 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 seems to go through all the cells, however I need 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());
    }
}
+3
source share
3 answers

Don't you want to remove the inner loop foreach? Or am I missing 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());
}
+5
source
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());
      }
   }
}
+3
source

, ColumnIndex? - .

if (cell.Value == null || cell.Value.Equals("") || cell.ColumnIndex != 2)
{
    continue;
}
+2

Source: https://habr.com/ru/post/1707540/


All Articles