NWOWN
NWOWN

Reputation: 409

ListView Grouping by Column Value

ListView like this

Name    |    IP        |  Port
--------------------------------
Alice   | 192.168.0.1  |  1000
Bob     | 192.168.0.1  |  1000
Carol   | 192.168.0.1  |  1000
Dave    | 192.168.0.2  |  2000
Eve     | 192.168.0.2  |  2000

I want grouping by IP like {Alice, Bob, Carol} and {Dave, Eve}

If it System.Collections.Generic.List, I use FindAll.

But it is ListViewItemCollection, How can I grouping?

The way I can think of is to create a new List by for loop with ListViewItemCollection.

Is there any other way?

Upvotes: 1

Views: 1605

Answers (1)

user10216583
user10216583

Reputation:

To group the ListViewItem objects in a ListView control:

  1. Group the SubItems of a given ColumnHeader.
  2. Create a new ListViewGroup for each group key and,
  3. Assign it to the Group property of the grouped ListViewItem objects.

Create a grouping method to apply that:

private void GroupListViewItems(int columnIndex)
{
    if (!listView1.Columns.Cast<ColumnHeader>()
        .Select(c => c.Index).Contains(columnIndex))
        return;

    listView1.BeginUpdate();
    listView1.Groups.Clear();

    var groups = listView1.Items.Cast<ListViewItem>()
        .GroupBy(x => x.SubItems[columnIndex].Text);

    foreach(var group in groups.OrderBy(x => x.Key))
    {
        var g = new ListViewGroup(group.Key);

        listView1.Groups.Add(g);
        group.ToList().ForEach(x => x.Group = g);
    }

    listView1.Columns.Cast<ColumnHeader>().ToList().ForEach(x => x.Width = -2);
    listView1.EndUpdate();
}

... and maybe an overload to pass the columns by their names:

private void GroupListViewItems(string columnName)
{
    var columnHeader = listView1.Columns.Cast<ColumnHeader>()
        .FirstOrDefault(x => x.Text.ToLower().Equals(columnName.ToLower()));

    if (columnHeader != null)
        GroupListViewItems(columnHeader.Index);
}

... call the method and pass the name/index of a ColumnHeader. To ungroup the items, just clear the ListView.Groups property.

SOQ61998298

Upvotes: 2

Related Questions