Jarad Mayers
Jarad Mayers

Reputation: 73

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.

Upvotes: 2

Views: 5860

Answers (2)

Chris
Chris

Reputation: 915

Firstly create a class to hold your person information because how you are initializing your lists isn't good.

Public class Person
{
    public string Firstname {get; set;}
    public string Surname {get; set;}
    public int Age {get; set;}
}

Then you can create multiple people and store them in a list of type Person...e.g

//other code
List<Person> People = new List<Person>();
People.Add(new Person() { Firstname = "John", Surname = "Doe", Age = 19 });
//etc

Then in XAML all you have to do is point your Data grid at the People list and it should be able to bind to the various properties on each person or auto generate columns.

<DataGrid CanUserSortColumns="True" 
          CanUserAddRows="False"
          CanUserDeleteRows="False" 
          AutoGenerateColumns="False"
          ItemsSource="{Binding Path=People}"
          SelectionMode="Single">

    <DataGrid.Columns>
         <DataGridTextColumn     MinWidth="100"
                                         Width="Auto"
                                         IsReadOnly="False"
                                         Header="Firstname">
                                    <DataGridTextColumn.Binding>
                                        <Binding Path="Firstname"/>
                                    </DataGridTextColumn.Binding>
                  </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

untested XAML but should give you a starting point

There are plenty of guides online that will be able to help with this instead of writing your own question on Stack Overflow.

Upvotes: 1

ASh
ASh

Reputation: 35646

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;

Upvotes: 3

Related Questions