如何使用c#在DataGrid(WPF)中显示列表列表 [英] How to display a list of list in DataGrid( WPF) using c#

查看:959
本文介绍了如何使用c#在DataGrid(WPF)中显示列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标题(列)列表,然后是数据行,并希望通过两种方式在DataGrid中显示它

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 <

我非常感谢您。

推荐答案

鉴于标头的数量可能有所不同,我建议转换为便于双向数据绑定的格式的数据并使用DataTable:

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;

这篇关于如何使用c#在DataGrid(WPF)中显示列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆