How to Iterate Through the DataGrid

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


Similar Articles