Reader Level:
Article
Windows Forms

How to Iterate Through the DataGrid

By sailaja on Feb 09 2005
In this article, we will show how to iterate through the DataGrid.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 57.5k
  • 0

Most of the cases we need to traverse through the DataGrid .

Here is the code snippet for that :

private void button1_Click(object sender, System.EventArgs e)
{
CurrencyManager cm = (CurrencyManager)
this.BindingContext[this.dataGrid1.DataSource];
int rowCount = cm.Count;
//assumes datasource is a datatable...
int colCount = ((DataTable)this.dataGrid1.DataSource).Columns.Count;
for(int row = 0; row < rowCount; row++)
{
for(int col = 0; col < colCount; col++)
{
object cellValue = this.dataGrid1[row, col];
Console.Write(cellValue.ToString() + " ");
}
Console.WriteLine("");
}
}
{
CurrencyManager cm = (CurrencyManager)
this.BindingContext[this.dataGrid1.DataSource];
int rowCount = cm.Count;
//assumes datasource is a datatable...
int colCount = ((DataTable)this.dataGrid1.DataSource).Columns.Count;
for(int row = 0; row < rowCount; row++)
{
for(int col = 0; col < colCount; col++)
{
object cellValue = this.dataGrid1[row, col];
Console.Write(cellValue.ToString() + " ");
}
Console.WriteLine("");
}
}