用列表绑定字典的优雅方式

时间:2014-06-17 18:16:53

标签: c# winforms

其他然后分解,有一个简单的方法:

var dict = new Dictionary<string, List<string>>();

并将其绑定到winforms中的gridview控件?

3 个答案:

答案 0 :(得分:2)

这不是GridView,但是分组的ListView可以提供非常好的结果:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;

namespace so
{
    public class Program
    {
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }

    public class Form1 : Form
    {
        ListView lv;

        public Form1()
        {
            lv = new ListView 
                 { 
                    Parent = this, 
                    Dock = DockStyle.Fill, 
                    ShowGroups = true, 
                    View = View.Details
                 };
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var dic = new Dictionary<string, List<string>>()
            {
                { "group 1", new[] { "sorry", "for having voted", "close for duplicate", "too fast" }.ToList() },
                { "group 2", new[] { "this is not", "a gridview", "but the result", "looks like" }.ToList() },
                { "group 3", new[] { "what you", "are trying", "to achieve" }.ToList() },
                { "group 4", new[] { "hope", "it", "helps" }.ToList() }
            };

            lv.BeginUpdate();

            lv.Columns.Clear();
            lv.Columns.Add("Text");

            lv.Groups.Clear();
            lv.Groups.AddRange(
                dic.Keys.Select(
                    s => new ListViewGroup(s, s)).ToArray());

            lv.Items.Clear();
            lv.Items.AddRange(
                dic.SelectMany(kv => 
                    kv.Value.Select(item => 
                        new ListViewItem
                            { 
                                Text = item,
                                Group = lv.Groups[kv.Key]
                            })).ToArray());

            lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

            lv.EndUpdate();
        }
    }
}

答案 1 :(得分:1)

在datagrid中显示的一种方法是创建2列,并为列表中的每个值添加一行:

 private void button1_Click(object sender, EventArgs e)
    {
        //Create a Datatable
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("Col1");
        dataTable.Columns.Add("Col2");
        //For each key pair
        foreach (KeyValuePair<string, List<string>> keyValuePair in dict)
        {
            List<string> list = keyValuePair.Value;
            //Add a row for the each item in list
            foreach (var item in list)
            {
                DataRow row = dataTable.NewRow();
                row["Col1"] = keyValuePair.Key;
                row["Col2"] = item;
                dataTable.Rows.Add(row);    
            }
        }

        this.dataGridView1.DataSource = dataTable;
    }

答案 2 :(得分:0)

你没有告诉输出必须如何,例如:

    private void ElegantwaytoBindDictionarywithList()
    {
        var dict = new Dictionary<string, List<string>>
        {
            {
                "Foo", new List<string>{"foo1","foo2"}
            },
            {
                "Bar", new List<string>{"bar1","bar2"}
            }
        };

        var source = new BindingSource {DataSource = dict};

        dataGridView1.RowsAdded += (sender, args) =>
        {
            var key = dict.Skip(args.RowIndex).First().Key;

            dataGridView1.Rows[args.RowIndex].Cells["value"].Value = string.Join(", ", dict[key]);
        };

        dataGridView1.Columns.Add("value", "value");
        dataGridView1.DataSource = source;
    }

enter image description here