Share via


如何:在 Windows Form ListView 控制項中群組項目

透過控制項的 ListView 群組功能,您可以在群組中顯示相關的專案集。 這些群組會依包含群組標題的水準群組標頭在畫面上分隔。 您可以使用 ListView 群組,透過依字母順序、依日期或任何其他邏輯群組來分組專案,讓流覽大型清單更容易。 下圖顯示一些分組的專案。

Screenshot of odd and even ListView groups.

若要啟用群組,您必須先在設計工具中或以程式設計方式建立一或多個群組。 定義群組之後,您可以將專案指派 ListView 給群組。 您也可以以程式設計方式將專案從一個群組移至另一個群組。

若要新增群組

  1. 使用 Add 集合的 Groups 方法。

    // Adds a new group that has a left-aligned header
    listView1.Groups.Add(new ListViewGroup("List item text",
        HorizontalAlignment.Left));
    
    ' Adds a new group that has a left-aligned header
    ListView1.Groups.Add(New ListViewGroup("Group 1", _
     HorizontalAlignment.Left))
    

移除群組

  1. RemoveAt使用 集合的 GroupsClear 方法。

    方法 RemoveAt 會移除單一群組; Clear 方法會從清單中移除所有群組。

    注意

    移除群組並不會移除該群組內的專案。

    // Removes the first group in the collection.
    listView1.Groups.RemoveAt(0);
    // Clears all groups.
    listView1.Groups.Clear();
    
    ' Removes the first group in the collection.
    ListView1.Groups.RemoveAt(0)
    ' Clears all groups:
    ListView1.Groups.Clear()
    

將專案指派給群組,或在群組之間移動專案

  1. ListViewItem.Group設定個別專案的 屬性。

    // Adds the first item to the first group
    listView1.Items[0].Group = listView1.Groups[0];
    
    ' Adds the first item to the first group
    ListView1.Items.Item(0).Group = ListView1.Groups(0)
    

另請參閱