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

Platform: WinForms| Category: Datagrid

To iterate through all rows and columns in a WinForms DataGrid, you can access the underlying data using the grid’s view records and columns. The following code example demonstrates how to achieve this by looping through each record and column, retrieving its cell values and printing them to the console.

[C#]

private void button1_Click(object sender, EventArgs e)
{
     int rowCount = sfDataGrid1.View.Records.Count;
     int colCount = sfDataGrid1.Columns.Count;

     for (int row = 0; row < rowCount; row++)
     {
         var record = sfDataGrid1.View.Records[row].Data;
         for (int col = 0; col < colCount; col++)
         {
             var columnName = sfDataGrid1.Columns[col].MappingName;
             var property = record.GetType().GetProperty(columnName);
             var cellValue = property.GetValue(record);
             Console.Write(cellValue?.ToString() + " ");
         }
         Console.WriteLine();
     }
}

[VB.NET]

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click
      Dim rowCount As Integer = sfDataGrid1.View.Records.Count
      Dim colCount As Integer = sfDataGrid1.Columns.Count

      For row As Integer = 0 To rowCount - 1
            Dim record = sfDataGrid1.View.Records(row).Data
            For col As Integer = 0 To colCount - 1
                  Dim columnName = sfDataGrid1.Columns(col).MappingName
                  Dim [property] = record.GetType().GetProperty(columnName)
                  Dim cellValue = [property].GetValue(record)
                  Console.Write(cellValue?.ToString() & " ")
            Next col
            Console.WriteLine()
      Next row
End Sub

Share with

Related FAQs

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

Please submit your question and answer.