我有动态列表项。这个列表不是静态的。鉴于需要,我将至少有一个/多个列表。我需要的是,我必须将该列表分成至少两个唯一记录。这个我可以分开。然而,我需要将此列表绑定(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 中,
如何将数据源添加到此数据 GridView ?我厌倦了将其包含到数据表中。无论如何,我无法做到这一点。任何帮助都会得到真正的重视。
最佳答案
您可以创建一个 BooK
在 List<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;
结果如下:
关于c# - 在c#中将不同的列表绑定(bind)到datagridview中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34217569/