2

我正在 Visual Studio 2017 中创建一个 winforms 应用程序,我正在使用

 List<KeyValuePair<string, string>>

数据示例如下:

 List<KeyValuePair<ABC, 123>>
 List<KeyValuePair<ABC, 456>>
 List<KeyValuePair<ABC, 789>>
 List<KeyValuePair<DEF, 123>>
 List<KeyValuePair<DEF, 233>>

我尝试在 ListView 中显示它,我希望在其中有这样的东西:

  • 美国广播公司

    • 123
    • 456
    • 789
  • 国防军

    • 123
    • 233

其中 ABC 和 DEF 只能选择。我尝试编写代码来执行此操作,但不幸的是它只显示没有子项的 ABC 和 DEF。

我写的代码是:

         workOrderClusters = GetItac.FilterWorkOrderClusters();
        // GetItac.FilterWorkOrderClusters() is a  
        List<KeyValuePair<string,string>>
        string current; string previous,
        foreach (var workOrderCluster in workOrderClusters)
        {
            current = workOrderCluster.Key;
            if (current != previous)
            {
                var listViewItem = new ListViewItem(workOrderCluster.Key);
                foreach (var cluster in workOrderClusters)
                {
                    if (cluster.Key == current)
                    {
                        listViewItem.SubItems.Add(cluster.Value);
                    }
                }
            }
            previous = current;
            listView1.Items.Add(listViewItem);

我的问题是,有没有让 ListView 按预期显示?

4

1 回答 1

2

ListView如果它在Details视图中并且它有一些列,则显示子项目。

假设您有以下数据:

var list = new List<KeyValuePair<string, int>>(){
    new KeyValuePair<string, int>("ABC", 123),
    new KeyValuePair<string, int>("ABC", 456),
    new KeyValuePair<string, int>("ABC", 789),
    new KeyValuePair<string, int>("DEF", 123),
    new KeyValuePair<string, int>("DEF", 233),
};

要将数据结构转换为ListView项目,您可以首先根据键对数据进行分组:

var data = list.GroupBy(x => x.Key).Select(x => new
    {
        Key = x.Key,
        Values = x.Select(a => a.Value)
    });

然后将项目和子项目添加到控件中:

foreach(var d in data)
{
    var item = listView1.Items.Add(d.Key);
    foreach (var v in d.Values)
        item.SubItems.Add(v.ToString());
}

然后设置ListView显示它们:

listView1.View = View.Details;
var count = data.Max(x => x.Values.Count());
for (int i = 0; i <= count; i++)
    listView1.Columns.Add($"Column {i+1}");

笔记

正如评论中也提到的,可能TreeView更适合显示此类数据。如果您想将该数据添加到TreeView,在分组数据后,您可以使用以下代码:

foreach (var d in data)
{
    var node = treeView1.Nodes.Add(d.Key);
    foreach (var v in d.Values)
        node.Nodes.Add(v.ToString());
}
于 2018-06-12T15:24:56.717 回答