- List View. List View Item Collection. Add Метод
- Определение
- Перегрузки
- Add(String)
- Параметры
- Возвращаемое значение
- Комментарии
- См. также раздел
- Применяется к
- Add(ListViewItem)
- Параметры
- Возвращаемое значение
- Комментарии
- См. также раздел
- Применяется к
- Add(String, Int32)
- Параметры
- Возвращаемое значение
- Элемент управления ListView (Windows Forms) ListView Control (Windows Forms)
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- Общие сведения об элементе управления ListView (Windows Forms) ListView Control Overview (Windows Forms)
- Что можно сделать с помощью элемента управления ListView What You Can Do with the ListView Control
List View. List View Item Collection. Add Метод
Определение
Добавляет элемент в коллекцию элементов. Adds an item to the collection of items.
Перегрузки
Создает элемент с заданным текстом и добавляет его в коллекцию. Creates an item with the specified text and adds it to the collection.
Добавляет существующий ListViewItem в коллекцию. Adds an existing ListViewItem to the collection.
Создает элемент с заданным текстом и изображением и добавляет его в коллекцию. Creates an item with the specified text and image and adds it to the collection.
Создает элемент с заданным текстом и изображением и добавляет его в коллекцию. Creates an item with the specified text and image and adds it to the collection.
Создает элемент с заданным ключом, текстом и изображением и добавляет этот элемент в коллекцию. Creates an item with the specified key, text, and image and adds an item to the collection.
Создает элемент с заданным ключом, текстом и изображением и добавляет этот элемент в коллекцию. Creates an item with the specified key, text, and image, and adds it to the collection.
Add(String)
Создает элемент с заданным текстом и добавляет его в коллекцию. Creates an item with the specified text and adds it to the collection.
Параметры
Текст, отображаемый для элемента. The text to display for the item.
Возвращаемое значение
Объект ListViewItem, добавленный в коллекцию. The ListViewItem that was added to the collection.
Комментарии
Эту версию метода можно использовать Add для создания нового объекта ListViewItem для добавления в ListView элемент управления. You can use this version of the Add method to create a new ListViewItem to add to a ListView control. Текст нового ListViewItem элемента, добавленного в элемент управления, основан на text параметре. The text of the new ListViewItem added to the control is based on the text parameter. Если необходимо указать изображение для элемента, используйте версию Add метода, который принимает индекс изображения в качестве параметра. If you want to specify an image for the item, use the version of the Add method that accepts an image index as a parameter. Если у вас есть существующий объект ListViewItem , который необходимо добавить в коллекцию, используйте версию Add метода, принимающего в ListViewItem качестве параметра. If you have an existing ListViewItem that you want to add to the collection, use the version of the Add method that accepts a ListViewItem as its parameter.
Если ListView.Sorting свойству присвоено значение, отличное от SortOrder.None , или если ListViewItemSorter свойство задано, список сортируется после добавления элемента. If the ListView.Sorting property is set to a value other than SortOrder.None or if the ListViewItemSorter property is set, the list is sorted after the item is added. В противном случае элемент вставляется в конец списка. Otherwise, the item is inserted at the end of the list. Если список не отсортирован, можно использовать Insert метод для вставки элемента в ListView заданную позицию. If the list is not sorted, you can use the Insert method to insert an item into the ListView at a specific position. Чтобы добавить набор элементов в элемент управления за одну операцию, используйте AddRange метод. To add a set of items to the control in a single operation, use the AddRange method. Если вы хотите использовать Add метод для добавления большого количества элементов в элемент управления, используйте BeginUpdate методы и, EndUpdate чтобы предотвратить ListView перерисовку, пока не будут добавлены все элементы. If you want to use the Add method to add a large number of items to the control, use the BeginUpdate and EndUpdate methods to prevent the ListView from repainting until all items are added. При добавлении элементов в ListView , более эффективно сортировать элементы сначала, а затем добавлять новые элементы. When adding items to a ListView, it is more efficient to sort the items first and then add new items.
См. также раздел
Применяется к
Add(ListViewItem)
Добавляет существующий ListViewItem в коллекцию. Adds an existing ListViewItem to the collection.
Параметры
Параметр ListViewItem для добавления в коллекцию. The ListViewItem to add to the collection.
Возвращаемое значение
Объект ListViewItem, добавленный в коллекцию. The ListViewItem that was added to the collection.
Комментарии
Эту версию метода можно использовать Add для добавления существующего объекта ListViewItem в коллекцию. You can use this version of the Add method to add an existing ListViewItem to the collection. Эта версия Add метода обычно используется для повторного использования элементов из других ListView элементов управления или, если объект ListViewItem был создан вручную перед его добавлением в коллекцию. This version of the Add method is typically used to reuse items from other ListView controls or if the ListViewItem was created manually before adding it to the collection. Если вы хотите создать новый ListViewItem вместо использования существующего элемента, используйте другие версии Add метода. If you want to create a new ListViewItem instead of using an existing item, use the other versions of the Add method.
Если ListView.Sorting свойству присвоено значение, отличное от SortOrder.None , или если ListViewItemSorter свойство задано, список сортируется после добавления элемента. If the ListView.Sorting property is set to a value other than SortOrder.None or if the ListViewItemSorter property is set, the list is sorted after the item is added. В противном случае элемент вставляется в конец списка. Otherwise, the item is inserted at the end of the list. Если список не отсортирован, можно использовать Insert метод для вставки элемента в ListView заданную позицию. If the list is not sorted, you can use the Insert method to insert an item into the ListView at a specific position. Чтобы добавить набор элементов в элемент управления за одну операцию, используйте AddRange метод. To add a set of items to the control in a single operation, use the AddRange method. Если вы хотите использовать Add метод для добавления большого количества элементов в элемент управления, используйте BeginUpdate методы и, EndUpdate чтобы предотвратить ListView перерисовку, пока не будут добавлены все элементы. If you want to use the Add method to add a large number of items to the control, use the BeginUpdate and EndUpdate methods to prevent the ListView from repainting until all items are added. При добавлении элементов в ListView , более эффективно сортировать элементы сначала, а затем добавлять новые элементы. When adding items to a ListView, it is more efficient to sort the items first and then add new items.
Эта версия Add метода также используется для присвоения значения ListViewItem ListViewGroup . This version of the Add method is also used to assign a ListViewItem to a ListViewGroup.
См. также раздел
Применяется к
Add(String, Int32)
Создает элемент с заданным текстом и изображением и добавляет его в коллекцию. Creates an item with the specified text and image and adds it to the collection.
Параметры
Текст данного элемента. The text of the item.
Индекс изображения для данного элемента. The index of the image to display for the item.
Возвращаемое значение
Объект ListViewItem, добавленный в коллекцию. The ListViewItem that was added to the collection.
Элемент управления ListView (Windows Forms) ListView Control (Windows Forms)
Элемент управления ListView Windows Forms отображает список элементов со значками. The Windows Forms ListView control displays a list of items with icons. Представление списка можно использовать для создания пользовательского интерфейса, аналогичного правой области окна проводника. You can use a list view to create a user interface like the right pane of Windows Explorer.
в этом разделе In This Section
Общие сведения об элементе управления ListView ListView Control Overview
Описывается элемент управления, его основные возможности и свойства. Describes this control and its key features and properties.
Практическое руководство. Добавление столбцов в элемент управления ListView в Windows Forms How to: Add Columns to the Windows Forms ListView Control
Описывается, как создавать столбцы для вывода сведений о каждом элементе списка. Describes how to create columns in order to display information about each list item.
Практическое руководство. Отображение значков в элементе управления ListView в Windows Forms How to: Display Icons for the Windows Forms ListView Control
Описывается, как связать представление списка с соответствующим списком изображений для отображения крупных или мелких значков. Describes how to associate a list view with an appropriate image list for displaying large or small icons.
Практическое руководство. Группирование элементов в элементе управления ListView в формах Windows Forms How to: Group Items in a Windows Forms ListView Control
Описывается, как создать группы для отображения по категориям и как назначить элементы каждой группе. Describes how to create groups for categorized display and how to assign items to each group.
Практическое руководство. Отображение содержимого элемента управления ListView в Windows Forms в виде мозаичного представления How to: Enable Tile View in a Windows Forms ListView Control
Описывается, как отобразить элементы в виде плиток, каждая из которых состоит из большого значка и нескольких строк текста. Describes how to display items as tiles, each of which is comprised of a large icon and multiple lines of text.
Практическое руководство. Индикация места вставки в элементе управления ListView в Windows Forms How to: Display an Insertion Mark in a Windows Forms ListView Control
Описывается, как реализовать обратную связь с пользователем при выполнении операций перетаскивания, в ходе которых метка вставки указывает место перетаскивания для каждого положения указателя мыши. Describes how to implement user-feedback for drag-and-drop operations in which an insertion mark indicates the drop location for each mouse-pointer position.
Практическое руководство. Добавление в элемент управления ListView возможностей поиска How to: Add Search Capabilities to a ListView Control
Описывается, как программным способом найти элемент с помощью текстового поиска или экранных координат. Describes how to programmatically find an item using either text search or screen coordinates.
Справочник Reference
Класс ListView ListView class
Описание класса и всех его членов. Describes this class and has links to all its members.
Связанные разделы Related Sections
Практическое руководство. Добавление пользовательских данных в элемент управления TreeView или ListView (Windows Forms) How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)
Описывается, как выполнять наследование от элемента в представлении списка или узла дерева для добавления любых необходимых полей, методов или конструкторов. Describes how to inherit from an item in a list view or a node in a tree view in order to add any fields, methods, or constructors you need.
Компонент ImageList ImageList Component
Описание списка изображений, его основных возможностей и свойств. Explains what an image list is and its key features and properties.
Общие сведения об элементе управления ListView (Windows Forms) ListView Control Overview (Windows Forms)
Элемент управления ListView Windows Forms отображает список элементов со значками. The Windows Forms ListView control displays a list of items with icons. Представление списка можно использовать для создания пользовательского интерфейса, аналогичного правой области окна проводника. You can use a list view to create a user interface like the right pane of Windows Explorer. Элемент управления имеет четыре режима представления: LargeIcon, маленькие значки, List и Details. The control has four view modes: LargeIcon, SmallIcon, List, and Details.
Что можно сделать с помощью элемента управления ListView What You Can Do with the ListView Control
Дополнительный режим просмотра, плитка, доступен только в Windows XP и операционной системе Windows Server 2003. An additional view mode, Tile, is only available on Windows XP and the Windows Server 2003 operating system. Дополнительные сведения см. в разделе инструкции. Включение мозаичного представления в Windows Forms элементе управления ListView. For more information, see How to: Enable Tile View in a Windows Forms ListView Control.
В режиме LargeIcon рядом с текстом элемента отображаются крупные значки. элементы отображаются в нескольких столбцах, если элемент управления достаточно большой. The LargeIcon mode displays large icons next to the item text; the items appear in multiple columns if the control is large enough. Режим маленькие значки одинаковый, за исключением того, что он отображает небольшие значки. The SmallIcon mode is the same except that it displays small icons. Режим списка отображает небольшие значки, но всегда находится в одном столбце. The List mode displays small icons but is always in a single column. В режиме подробностей отображаются элементы в нескольких столбцах. The Details mode displays items in multiple columns. Дополнительные сведения см. в разделе инструкции. Добавление столбцов в Windows Forms элемент управления ListView. For details, see How to: Add Columns to the Windows Forms ListView Control. Режим просмотра определяется View свойством. The view mode is determined by the View property. Все режимы просмотра могут отображать изображения из списков изображений. All of the view modes can display images from image lists. Дополнительные сведения см. в разделе как отображать значки для элемента управления ListView Windows Forms. For details, see How to: Display Icons for the Windows Forms ListView Control.
В следующей таблице перечислены некоторые ListView элементы и представления, которые они являются допустимыми. The following table lists some of the ListView members and the views they are valid in.
Элемент ListView ListView member | Просмотр View |
---|---|
СвойствоAlignment Alignment property | SmallIcon либо LargeIcon SmallIcon or LargeIcon |
СвойствоAutoArrange AutoArrange property | SmallIcon либо LargeIcon SmallIcon or LargeIcon |
Метод AutoResizeColumn AutoResizeColumn method | Details |
СвойствоColumns Columns property | Details либо Tile Details or Tile |
СобытиеDrawSubItem DrawSubItem event | Details |
Метод FindItemWithText FindItemWithText method | Details, Listили Tile Details, List, or Tile |
Метод FindNearestItem FindNearestItem method | SmallIcon либо LargeIcon SmallIcon or LargeIcon |
Метод GetItemAt GetItemAt method | Details либо Tile Details or Tile |
СвойствоGroups Groups property | Все представления, Кроме List All views except List |
СвойствоHeaderStyle HeaderStyle property | Details. Details. |
СвойствоInsertionMark InsertionMark property | LargeIcon, SmallIconили Tile LargeIcon, SmallIcon, or Tile |
Ключевым свойством ListView элемента управления является Items , который содержит элементы, отображаемые элементом управления. The key property of the ListView control is Items, which contains the items displayed by the control. SelectedItemsСвойство содержит коллекцию элементов, выбранных в данный момент в элементе управления. The SelectedItems property contains a collection of the items currently selected in the control. Пользователь может выбрать несколько элементов, например, чтобы перетащить несколько элементов за раз в другой элемент управления, если MultiSelect свойство имеет значение true . The user can select multiple items, for example to drag and drop several items at a time to another control, if the MultiSelect property is set to true . ListViewЭлемент управления может отображать флажки рядом с элементами, если CheckBoxes свойство имеет значение true . The ListView control can display check boxes next to the items, if the CheckBoxes property is set to true .
ActivationСвойство определяет тип действия, которое пользователь должен предпринять для активации элемента в списке: Standard , OneClick и TwoClick . The Activation property determines what type of action the user must take to activate an item in the list: the options are Standard, OneClick, and TwoClick. OneClick для активации элемента требуется одно нажатие кнопки. OneClick activation requires a single click to activate the item. TwoClick Активация требует, чтобы пользователь дважды щелкнул элемент, чтобы активировать его. один щелчок изменяет цвет текста элемента. TwoClick activation requires the user to double-click to activate the item; a single click changes the color of the item text. Standard Активация требует, чтобы пользователь дважды щелкнул, чтобы активировать элемент, но элемент не изменит внешний вид. Standard activation requires the user to double-click to activate an item, but the item does not change appearance.
ListViewЭлемент управления также поддерживает стили оформления и другие возможности, доступные на платформе Windows XP, включая группирование, мозаичное представление и метки вставки. The ListView control also supports the visual styles and other features available on the Windows XP platform, including grouping, tile view, and insertion marks.