Live Chat Icon For mobile
Live Chat Icon

How do I iterate through all the rows and columns in my datagrid

Platform: WinForms| Category: Datagrid

You use the row index and column index as indexers on the DataGrid object.

[C#]
	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('');
		}
	}

[VB.NET]
	Private Sub button1_Click(sender As Object, e As System.EventArgs)
   		Dim cm As CurrencyManager = CType(Me.BindingContext(Me.dataGrid1.DataSource), CurrencyManager)
   
   		Dim rowCount As Integer = cm.Count
   		’assumes datasource is a datatable...
  		 Dim colCount As Integer = CType(Me.dataGrid1.DataSource, DataTable).Columns.Count
   
   		Dim row As Integer
   		For row = 0 To rowCount - 1
      			Dim col As Integer
      			For col = 0 To colCount - 1
         				Dim cellValue As Object = Me.dataGrid1(row, col)
         				Console.Write((cellValue.ToString() + '  '))
      			Next col
      			Console.WriteLine('')
   		Next row
	End Sub ’button1_Click

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.