ListViewGroupCollection.Clear 方法

定義

移除集合中所有的群組。

public void Clear();

實作

範例

下列範例示範如何在 Clear 依詳細資料檢視中的子專案值來組織 ListView 專案的應用程式中使用 方法。 這種群組形式類似于 Windows 檔案總管中使用的群組。 在此範例中,會動態建立群組。 針對每個子專案資料行,會為每個唯一子專案值建立一個群組。 針對父專案資料行,會為每個唯一的初始字母建立一個群組。 針對每個資料行建立的群組會儲存在雜湊表中,以及子專案文字或初始字母。 按一下資料行標頭時,會 ListViewGroupCollection 清除 。 接著會擷取對應至所按一下資料行的雜湊表,並將每個專案指派給適當的群組。 最後,雜湊表中群組的已排序陣列會新增至 ListViewGroupCollection

如需完整的範例,請參閱 ListViewGroupCollection 概觀參考主題。

// Sets myListView to the groups created for the specified column.
private void SetGroups(int column)
{
    // Remove the current groups.
    myListView.Groups.Clear();

    // Retrieve the hash table corresponding to the column.
    Hashtable groups = (Hashtable)groupTables[column];

    // Copy the groups for the column to an array.
    ListViewGroup[] groupsArray = new ListViewGroup[groups.Count];
    groups.Values.CopyTo(groupsArray, 0);

    // Sort the groups and add them to myListView.
    Array.Sort(groupsArray, new ListViewGroupSorter(myListView.Sorting));
    myListView.Groups.AddRange(groupsArray);

    // Iterate through the items in myListView, assigning each 
    // one to the appropriate group.
    foreach (ListViewItem item in myListView.Items)
    {
        // Retrieve the subitem text corresponding to the column.
        string subItemText = item.SubItems[column].Text;

        // For the Title column, use only the first letter.
        if (column == 0) 
        {
            subItemText = subItemText.Substring(0, 1);
        }

        // Assign the item to the matching group.
        item.Group = (ListViewGroup)groups[subItemText];
    }
}

備註

使用這個方法可從集合中移除所有群組。 請注意,從 ListView.Groups 集合中移除群組並不會從 ListView 控制項中移除專案。

這個方法適用于停用群組功能。 當控制項中 ListView 沒有群組時,專案通常會顯示。 若要從集合中移除個別群組,請使用 RemoveRemoveAt 方法。

當您想要提供多種方式來群組專案時,此方法也很有用。 若要變更群組,請先使用 Clear 方法從集合中移除所有群組,然後使用 AddRange 方法新增不同的群組陣列。

適用於

產品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10