使用列表作为DataGridView的数据源

本文关键字:DataGridView 数据源 列表 | 更新日期: 2023-09-27 18:00:14

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

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

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

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

关于如何获得有序字典并将条目显示在标有"设置"answers"值"的两列中,有什么想法吗?我相信列表是与DataGridViews兼容的DataSource,但现在我开始怀疑自己了。

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

谢谢!

编辑

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

    List<myStruct> list = new List<myStruct>();
    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上没有显示任何内容,它只是空的。有人知道为什么吗?

使用列表作为DataGridView的数据源

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

我试过这个例子:

        var source = new BindingSource();
        List<MyStruct> list = new List<MyStruct> { 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;
        }

我为简单的数据库应用

写这篇文章