c# - 在c#中将不同的列表绑定(bind)到datagridview中的列

标签 c# .net winforms datagridview

我有动态列表项。这个列表不是静态的。鉴于需要,我将至少有一个/多个列表。我需要的是,我必须将该列表分成至少两个唯一记录。这个我可以分开。然而,我需要将此列表绑定(bind)到 datagridview。

这是我的代码:我有两个列表,

  List<string> list1=new List<string>();
  list1.add("THE BOOK OF BURGER");
  list1.add("The Hogwarts Library");
  list1.add("NEW Day in the Life of a Farmer");

  List<string> list2=new List<string>();
  list2.add("$200");
  list2.add("$150");
  list2.add("$170");

  .....
  list3,
  list4.. etc..

我有 Datagridview。我想将其绑定(bind)到数据 GridView 中, enter image description here

如何将数据源添加到此数据 GridView ?我厌倦了将其包含到数据表中。无论如何,我无法做到这一点。任何帮助都会得到真正的重视。

最佳答案

您可以创建一个 BooKList<Book> 中对数据进行分类和整形并将网格绑定(bind)到列表。

public class Book
{
    public string Title { get; set; }
    public string Price { get; set; }
}

绑定(bind)数据到DataGridView

var list = new List<Book>();
for (int i = 0; i < list1.Count; i++)
{
    list.Add(new Book()
    {
        Title = list1[i],
        Price = list2[i]
    });
}

this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = list;

编辑

根据评论,我想你有一个 Dictionary<String, List<String>>并且您想将它们动态添加到网格中。

我想您将使用字典的键作为列的标题文本。

//Add your lists to the dictionary
var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("list1", list1);
dictionary.Add("list2", list2);
// And some othet lists ....

//Calculate the count of rows.
int rowCount = dictionary.Cast<KeyValuePair<string, List<string>>>()
                         .Select(x=>x.Value.Count).Max();

//Create the data table and for each table, add a column
var dataTable = new DataTable();
foreach (var key in dictionary.Keys)
{
    dataTable.Columns.Add(key);
}

//Add items of each list to the columns of rows of table
for (int i = 0; i < rowCount; i++)
{
    var row = dataTable.Rows.Add();
    foreach (var key in dictionary.Keys)
    {
        try
        {
            row[key] = dictionary[key][i];
        }
        catch 
        {
            row[key] = null;
        }
    }
}

//Show data in grid
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = dataTable;

结果如下:

enter image description here

关于c# - 在c#中将不同的列表绑定(bind)到datagridview中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34217569/

相关文章:

c# - 如何在c#中将PDF转换为WORD

c# - 为什么将 DoEvents 放入循环中会导致 StackOverflow 异常?

c# - JSON 字符串到 C# 中的模型/HashMap/字典

c# - 无法在使用 VS 2015 安装的 Windows 10 上以 64 位模式运行 ASP.NET 项目

c# - 从 IEnumerable foreach 循环中获取值

winforms - 从 pdf 查看器中提取文本和所有字体信息

c# - 将文本附加到文件路径

c# - 将可见性绑定(bind)到与 DataContext 不同的源

c# - WPF 多复选框选中/取消选中

c# - 哪个字符串操作更好?