使用列表作为DataGridView的数据源

我已经将配置文件中的设置名称及其各自的值提取到有序字典中。 字典包含ICollection类的键和值。 我想绑定该数据并将其显示在DataGridView中。 我已经尝试将字符串复制到数组并显示这些数组,但是当我运行程序时,列是空白的,它似乎根本没有绑定。

我还试图将DataGridView源直接设置为有序字典集合(键或值),但这也没有产生我想要的任何东西; 列仍然是空白的。 但是,第三列的列名称为“length”,并显示ICollection中条目的长度。 但不用说我不想要长度,我想要条目本身。

这是我用于此问题的代码:在加载表单时,我加载配置文件,名为m_Settings的私有成员具有所有键值对。 然后我创建一个列表并分别添加键和值。 将绑定源设置为’data’后,我运行程序,我添加的两个列都是空白的。

private void Form4_Load(object sender, EventArgs e) { loadconfigfile(Properties.Settings.Default.Config); List data = new List(); data.Add(m_Settings.Keys); data.Add(m_Settings.Values); bindingSource1.DataSource = data; dataGridView1.DataSource = bindingSource1; dataGridView1.Refresh(); } 

有关如何获取有序字典并在标有“设置”和“值”的两列中显示条目的任何想法? 我相信列表是DataGridViews兼容的DataSources,但现在我开始猜测自己了。

任何帮助或方向非常感谢! 如果需要,我很乐意提供更多信息。

谢谢!

编辑

以下是已实现的myStruct类的修订代码:

  List list = new List(); for(int index = 0; index < m_Settings.Count; index++) { myStruct pair = new myStruct(keys[index], values[index].ToString()); list.Add(pair); } public class myStruct { private string Key { get; set; } private string Value { get; set; } public myStruct(string key, string value) { Key = key; Value = value; } } 

但是,当我将绑定DataDource设置为list时,DataGridView上没有任何内容,它只是空的。 谁知道为什么?

首先,我不明白为什么要添加所有键和值计数次数,从不使用索引。

我试过这个例子:

  var source = new BindingSource(); List list = new List { new MyStruct("fff", "b"), new MyStruct("c","d") }; source.DataSource = list; grid.DataSource = source; 

而且工作得很好,我得到两个正确名称的列。 MyStruct类型公开绑定机制可以使用的属性。

  class MyStruct { public string Name { get; set; } public string Adres { get; set; } public MyStruct(string name, string adress) { Name = name; Adres = adress; } } 

尝试构建一个带有一个键和值的类型,然后逐个添加它。 希望这可以帮助。

设置DataGridView属性

  gridView1.AutoGenerateColumns = true; 

并确保您绑定的对象列表,这些对象属性应该是公共的。

这个Func可以帮到你。 它将每个列表对象添加到网格视图

 private void show_data() { BindingSource Source = new BindingSource(); for (int i = 0; i < CC.Contects.Count; i++) { Source.Add(CC.Contects.ElementAt(i)); }; Data_View.DataSource = Source; } 

我为简单的数据库应用写这个