ListViewGroupCollection methods throw new InvalidOperationException

Previously, an InvalidOperationException was thrown if ListViewGroupCollection methods were invoked on a ListView in virtual mode and the Handle had already been created. Starting in .NET 6, these ListViewGroupCollection methods now only check if the ListView is in virtual mode. If it is, they throw an InvalidOperationException with a more descriptive message.

Previous behavior

Consider the following code that adds a ListViewGroup to a ListView:

ListViewGroup group1 = new ListViewGroup
{
    Header = "CollapsibleGroup1",
    CollapsedState = ListViewGroupCollapsedState.Expanded
};

listView.Groups.Add(group1);

This code produced an InvalidOperationException with the following message:

When the ListView is in virtual mode, you cannot enumerate through the ListView items collection using an enumerator or call GetEnumerator. Use the ListView items indexer instead and access an item by index value.

New behavior

The same code from the Previous behavior section produces an InvalidOperationException with the following message:

You cannot add groups to the ListView groups collection when the ListView is in virtual mode.

Change category

This change affects binary compatibility.

Reason for change

The new InvalidOperationException message is more understandable. In addition, it closes a workaround where the developer could add a ListViewGroup to the ListView before the Handle was created.

Version introduced

.NET 6 RC 2

Affected APIs