System windows forms listview

List View. View Property

Definition

Gets or sets how items are displayed in the control.

Property Value

One of the View values. The default is LargeIcon.

Exceptions

The value specified is not one of the View values.

Examples

The following code example creates a ListView control with three ListViewItem objects specified and three ListViewItem.ListViewSubItem objects specified for each item. The example also creates ColumnHeader objects to display the subitems in details view. Two ImageList objects are also created in the code example to provide images for the ListViewItem objects. These ImageList objects are added to the LargeImageList and SmallImageList properties. The example uses the following properties in creating the ListView control.

This example requires that you have added the code to a Form and call the method created in the example from the constructor or another method on the form. The example also requires that images named MySmallImage1 , MySmallImage2 , MyLargeImage1 , and MyLargeImage2 are located in the root directory of drive C.

Remarks

The View property allows you to specify the type of display the ListView control uses to display items. You can set the View property to display each item with large or small icons or display items in a vertical list. The richest option is the details view, which allows you to view not only the items but any subitems specified for each item. Each item is displayed in a grid, with each item listed vertically and the subitems for each item displayed in a column, with column headers. The details view is a perfect way to display database information to a user. With Windows XP and Windows Server 2003, you can also display items as tiles that balance graphical and textual information by showing a large icon along with subitem information of your choosing. To enable tile view, your application must call the Application.EnableVisualStyles method. The small-image view displays each item with an icon and textual information to the right of the icon. The large-image view displays each item with an icon and textual information below the icon. The size of the icons for the image list is specified by the ImageSize property of the ImageList for the SmallImageList or LargeImageList properties.

If you are using multiple image lists, for small and large icon view, with a ListView control, you should place small and large versions of the image at the same index location in their respective image lists. When switching between views, the index location of the image in one list is used to locate the image in the other list, regardless of the key value specified.

Most of the properties in the ListView control affect how the different views behave or are displayed. Some properties that affect the views of the items are only useful when the View property is set to a specific value, while others are useful in all views. For example, properties such as GridLines and FullRowSelect are only useful when the View property is set to View.Details, while the MultiSelect and CheckBoxes properties are useful in all views.

The following table shows some of the ListView members and the views they are valid in.

ListView member View
Alignment property SmallIcon or LargeIcon
AutoArrange property SmallIcon or LargeIcon
AutoResizeColumn method Details
CheckBoxes All views except Tile
Columns property Details or Tile
DrawSubItem event Details
FindItemWithText method Details, List, or Tile
FindNearestItem method SmallIcon or LargeIcon
GetItemAt method Details or Tile
Groups property All views except List
HeaderStyle property Details
InsertionMark property LargeIcon, SmallIcon, or Tile

You can use the View property to provide different views of data in your application, or to lock a specific view to utilize that view’s benefits. For example, the View property is often set to View.Details because the details view provides a number of viewing options not available in the other views.

If your ListView control does not have any column headers specified and you set the View property to View.Details, the ListView control will not display any items. If your ListView control does not have any column headers specified and you set the View property to View.Tile, the ListView control will not display any subitems.

The tile view displays each item with a large icon on the left and textual information on the right. The textual information consists of the item label followed by subitems. By default, only the first subitem is displayed, which corresponds to the item label. To display additional subitems, you must add ColumnHeader objects to the Columns collection. Each subitem in the tile corresponds to a column header. To control which subitems are displayed and the order in which they are displayed, you must set the ListViewItem.ListViewSubItem.Name property for each item and the ColumnHeader.Name property for each header. You can then add, remove, and rearrange headers in the Columns collection to achieve the desired result.

To control the size of the tiles in the tile view, set the TileSize property. This is useful to prevent line-wrapping when subitem text is too long for a single line.

For an example of the tile view, see the TileSize property.

Although columns are only displayed in the details view, subitems without column headers will not display in either the details view or the tile view.

The tile view is available only on Windows XP and Windows Server 2003 when your application calls the Application.EnableVisualStyles method. On earlier operating systems, any code related to the tile view has no effect, and the ListView control displays in the large icon view. As a result, any code that depends on the tile view might not work correctly.

You might want to include code that determines whether tile view is available, and provide alternate functionality when it is unavailable. For example, when you use owner drawing to customize the appearance of ListView items in the tile view, you might want to use drawing code appropriate to the large icon view when running on operating systems that do not support the tile view.

List View. Begin Update Метод

Определение

Запрещает прорисовку элемента управления до вызова метода EndUpdate(). Prevents the control from drawing until the EndUpdate() method is called.

Примеры

В следующем примере кода демонстрируется инициализация ListView элемента управления для хранения флажков. The following code example demonstrates initializing a ListView control to contain check boxes. Также показано, как использовать BeginUpdate EndUpdate методы и. It also demonstrates how to use the BeginUpdate and EndUpdate methods. Чтобы выполнить этот пример, вставьте следующий код в форму, содержащую ListView имя ListView1 . To run this example, paste the following code into a form that contains a ListView named ListView1 . Вызовите InitializeListView метод из конструктора или Load метода формы. Call the InitializeListView method from the form’s constructor or Load method.

Комментарии

Предпочтительным способом добавления нескольких элементов в ListView является использование AddRange метода объекта ListView.ListViewItemCollection (доступ через Items свойство объекта ListView ). The preferred way to add multiple items to a ListView is to use the AddRange method of the ListView.ListViewItemCollection (accessed through the Items property of the ListView). Это позволяет добавить массив элементов в список в одной операции. This enables you to add an array of items to the list in a single operation. Однако, если требуется добавить элементы по одному с помощью Add метода ListView.ListViewItemCollection класса, можно использовать BeginUpdate метод, чтобы предотвратить перерисовку элемента управления при ListView каждом добавлении элемента. However, if you want to add items one at a time using the Add method of the ListView.ListViewItemCollection class, you can use the BeginUpdate method to prevent the control from repainting the ListView every time that an item is added. После завершения задачи добавления элементов в элемент управления вызовите EndUpdate метод, чтобы включить ListView перерисовку. When you have completed the task of adding items to the control, call the EndUpdate method to enable the ListView to repaint. Такой способ добавления элементов может предотвратить мерцание изображения ListView при добавлении в элемент управления большого числа элементов. This way of adding items can prevent flickered drawing of the ListView when lots of items are being added to the control.

Если BeginUpdate вызывается несколько раз, метод EndUpdate должен вызываться аналогичным числом раз. If BeginUpdate is called more than once, EndUpdate must be called an equivalent number of times. До тех пор пока EndUpdate ListView не будет перерисовываться последний вызов функции. Until the last call to EndUpdate the ListView will not repaint. Кроме этого, несколько вызовов BeginUpdate не оказывают никакого влияния. Other than this, multiple calls to BeginUpdate have no effect.

Пошаговое руководство. Создание интерфейса в стиле проводника с использованием элементов управления ListView и TreeView с помощью конструктора Walkthrough: Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer

Одним из преимуществ Visual Studio является возможность создания профессионально оформленных Windows Forms приложений в течение короткого промежутка времени. One of the benefits of Visual Studio is the ability to create professional-looking Windows Forms applications in a short of amount of time. Распространенным сценарием является создание пользовательского интерфейса с ListView TreeView элементами управления и, которые похожи на проводник Windows в операционных системах Windows. A common scenario is creating a user interface (UI) with ListView and TreeView controls that resembles the Windows Explorer feature of Windows operating systems. Проводник Windows отображает иерархическую структуру файлов и папок на компьютере пользователя. Windows Explorer displays a hierarchical structure of the files and folders on a user’s computer.

Создание формы, содержащей элемент управления ListView и TreeView To create the form containing a ListView and TreeView control

В меню Файл укажите Создать, затем нажмите Проект. On the File menu, point to New, and then click Project.

В диалоговом окне Новый проект сделайте следующее: In the New Project dialog box, do the following:

В категории выберите либо Visual Basic , либо Visual C#. In the categories, choose either Visual Basic or Visual C#.

В списке шаблонов выберите Windows Forms приложение. In the list of templates, choose Windows Forms Application.

Нажмите кнопку ОК. Click OK. Будет создан новый проект Windows Forms. A new Windows Forms project is created.

Добавьте в SplitContainer форму элемент управления и задайте для его Dock свойства значение Fill . Add a SplitContainer control to the form and set its Dock property to Fill.

Добавьте ImageList именованный элемент imageList1 в форму и используйте окно свойств, чтобы добавить два изображения: изображение папки и изображение документа в указанном порядке. Add an ImageList named imageList1 to the form and use the Properties window to add two images: a folder image and a document image, in that order.

Добавьте TreeView элемент управления с именем treeview1 в форму и разместите его в левой части SplitContainer элемента управления. Add a TreeView control named treeview1 to the form, and position it on the left side of the SplitContainer control. В окно свойств treeView1 выполните следующие действия. In the Properties window for treeView1 do the following:

Задайте для свойства Dock значение Fill. Set the Dock property to Fill.

Задайте свойству ImageList значение imagelist1. Set the ImageList property to imagelist1.

Добавьте ListView элемент управления с именем listView1 в форму и разместите его в правой части SplitContainer элемента управления. Add a ListView control named listView1 to the form, and position it on the right side of the SplitContainer control. В окно свойств listview1 выполните следующие действия. In the Properties window for listview1 do the following:

Установите свойство Dock в значение Fill. Set the Dock property to Fill.

Установите свойство View в значение Details. Set the View property to Details.

Откройте редактор коллекции Колумнхеадер, нажав кнопку с многоточием ( ) в Columns свойстве . Open the ColumnHeader Collection Editor by clicking the ellipses ( ) in the Columns property . Добавьте три столбца и задайте Text для них свойства Name , Type и Last Modified соответственно. Add three columns and set their Text property to Name , Type , and Last Modified , respectively. Нажмите кнопку ОК , чтобы закрыть диалоговое окно. Click OK to close the dialog box.

Задайте свойству SmallImageList значение imageList1. Set the SmallImageList property to imageList1.

Реализуйте код, чтобы заполнить TreeView узлы и подузлы. Implement the code to populate the TreeView with nodes and subnodes. Добавьте этот код в Form1 класс. Add this code to the Form1 class.

Поскольку в предыдущем коде используется пространство имен System.IO, добавьте соответствующий оператор using или Import в верхней части формы. Since the previous code uses the System.IO namespace, add the appropriate using or import statement at the top of the form.

Вызовите метод Set-up из предыдущего шага в конструкторе формы или Load методе обработки событий. Call the set-up method from the previous step in the form’s constructor or Load event-handling method. Добавьте этот код в конструктор формы. Add this code to the form constructor.

Обработайте NodeMouseClick событие для treeview1 и реализуйте код , который заполняется listview1 содержимым узла при щелчке узла. Handle the NodeMouseClick event for treeview1 , and implement the code to populate listview1 with a node’s contents when a node is clicked. Добавьте этот код в Form1 класс. Add this code to the Form1 class.

Если вы используете C#, убедитесь, что у вас есть NodeMouseClick событие, связанное с методом обработки событий. If you are using C#, make sure you have the NodeMouseClick event associated with its event-handling method. Добавьте этот код в конструктор формы. Add this code to the form constructor.

Тестирование приложения Testing the Application

Теперь можно проверить форму, чтобы убедиться, что она ведет себя так, как ожидалось. You can now test the form to make sure it behaves as expected.

Тестирование формы To test the form

Нажмите клавишу F5 для запуска приложения. Press F5 to run the application.

Вы увидите разделенную форму TreeView , содержащую элемент управления, который отображает каталог проекта слева, и ListView элемент управления с правой стороны с тремя столбцами. You will see a split form containing a TreeView control that displays your project directory on the left side, and a ListView control on the right side with three columns. Можно просмотреть, TreeView выбрав узлы каталога, и ListView заполнится содержимым выбранного каталога. You can traverse the TreeView by selecting directory nodes, and the ListView is populated with the contents of the selected directory.

Next Steps Next Steps

Это приложение предоставляет пример того, как можно использовать TreeView ListView вместе элементы управления и. This application gives you an example of a way you can use TreeView and ListView controls together. Дополнительные сведения об этих элементах управления см. в следующих разделах: For more information on these controls, see the following topics:

Читайте также:  Windows serial port bios
Оцените статью