Search code examples
c#wpfdatagrid

How to display a list of list in DataGrid( WPF) using c#


I have a List of headers(columns) and then rows of data and want to show it in DataGrid with two way bindings

List<string> headers = new List<string> { "FirstName", "LastName", "Age" };
List<string> row1 = new List<string> { "John", "Doe", "19" };
List<string> row2 = new List<string> { "Jane", "Doe", "21" };
List<string> row3 = new List<string> { "Suzie", "Q", "52" };
List<string> row4 = new List<string> { "No", "Body", "48" };

List<List<string>> tableValues =
 new List<List<string>> { row1, row2, row3, row4 };

The editor does not let me show List of List since it has multiple <

I appreciate any help.


Solution

  • given that number of headers may vary, I suggest to tranform data in the format convenient for two-way data binding and use DataTable:

    var dt = new DataTable();
    
    // create columns and headers
    int columnCount = headers.Count;
    for (int i = 0; i < columnCount; i++)
        dt.Columns.Add(headers[i]);
    
    // copy rows data
    for (int i = 0; i < tableValues.Count; i++)
        dt.Rows.Add(tableValues[i].Take(columnCount).ToArray());
    
    // display in a DataGrid
    dataGrid.ItemsSource = dt.DefaultView;