Getting text only from a specific column of DataGridView
-
03-07-2019 - |
Question
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());
}
}
Solution
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());
}
OTHER TIPS
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());
}
}
}
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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow