SubItems of ListView are not displayed in winforms

578 views Asked by At

I am creating a winforms application in visual studio 2017, I am populating a ListView using a

 List<KeyValuePair<string, string>>

Examples of the data are:

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

I try to diplay this in a ListView, where I would like to have sometihng like this:

  • ABC

    • 123
    • 456
    • 789
  • DEF

    • 123
    • 233

Where the ABC and the DEF are selectable only. I try to write a code to do this, but unfortunately it only displays the ABC and DEF without the subitems.

The code I wrote is:

         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);

My question is, is there anyway to make the ListView display as expected ?

1

There are 1 answers

4
Reza Aghaei On BEST ANSWER

ListView shows sub items if it's in Details view and it has some columns.

Let's say you have the following data:

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),
};

To convert your data structure to ListView items you can first group data based on the key:

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

Then add items and sub items to the control:

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

And then setup ListView to show them:

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}");

Note

As also mentioned in the comments, probably TreeView is more suitable to show such data. In case you want to add that data to TreeView, after grouping data you can use the following code:

foreach (var d in data)
{
    var node = treeView1.Nodes.Add(d.Key);
    foreach (var v in d.Values)
        node.Nodes.Add(v.ToString());
}