Listview c как заполнить таблицу

от admin

Overview

This article will show how to fill a ListView Control with the data loaded into a DataSet . You may use a DataSet bind it to a Grid Control to show the output of a query, but data binding of controls is not always the ideal method of accessing the data (You may encounter problems with the DataBinding). A DataSet maintains a copy of the entire resultset in the client systems memory in case you need to make changes to a row. Instead of using a bound grid and a DataSet, we can use the listview control with the view set to details mode and fill it with the data from a DataSet.

Sorting the ListView

When you are working with the ListView control, you may want to sort its contents based on a specific column. An example of this kind of functionality occurs in a Windows Explorer program when you view the contents of a folder on your hard disk. In Details view, Windows Explorer displays information about the files in that folder. For example, you see the file name, the file size, the file type, and the date that the file was modified. When you click one of the column headers, the list is sorted in ascending order based on that column. When you click the same column header again, the column is sorted in descending order.

The ListView Control

The example in this article defines a class that inherits from the IComparer interface. Additionally, this example uses the Compare method of the CaseInsenstiveComparer class to perform the actual comparison of the items. Note that this method of comparison is not case sensitive («Apple» is considered to be the same as «apple»). Also, note that all of the columns in this example are sorted in a «text» manner.

The ListView control is a great way to display file system information and data from an XML file or database. The ListView control is typically used to display a graphical icon that represents the item, as well as the item text. In addition, the ListView control can be used to display additional information about an item in a subitem . For example, if the ListView control is displaying a list of files, you can configure the ListView control to display details such as file size and attributes as subitems. To display subitem information in the ListView control, you must set the View property to View.Details . In addition, you must create ColumnHeader objects and assign them to the Columns property of the ListView control. Once these properties are set, items are displayed in a row and column format that is similar to a DataGrid control. The ability to display items in this way makes the ListView control a quick and easy solution for displaying data from any type of data source.

Sorting for the ListView control is provided by using the Sorting property of the ListView. This enables you define the type of sorting to apply to the items. This is a great feature if you want to sort only by items. If you want to sort by subitems, you must use the custom sorting features of the ListView control . This article will demonstrate how to perform custom sorting in the ListView control and how to handle special data-type conditions when sorting.

Custom Sorting Features of the ListView Control

The ListView control provides features that enable you to use sorting other than that provided by the Sorting property. When the ListView control sorts items using the Sorting property, it uses a class that implements the System.Collections.IComparer interface. This class provides the sorting features used to sort each item. In order to sort by subitems, you must create your own class that implements the IComparer interface that in turn implements the sorting your ListView control needs. The class is defined with a constructor that specifies the column by which the ListView control is sorted. Once you have created this class, typically as a nested class of your form, you create an instance of this class and assign it to the ListViewItemSorter property of the ListView. This identifies the custom sorting class that the ListView control will use when the Sort method is called. The Sort method performs the actual sorting of the ListView items.

Initializing the Control

To begin, create an instance of a ListView control and add it to a form. After the control is on the form, add items to the ListView control using the Items property. You can add as many items as you want; just be sure that each item’s text is unique . While you are creating the items, add s ubitems for each. The following table is an example of how this information might look in the ListView control.

Item Subitem 1 Subitem 2
. . . 5
. . .
. . .

// Initialize ListView
private void InitializeListView()
<
// Set the view to show details.
listView1.View = View.Details;

// Allow the user to edit item text.
listView1.LabelEdit = true;

// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;

// Select the item and subitems when selection is made.
listView1.FullRowSelect = true;

// Display grid lines.
listView1.GridLines = true;

// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;

// Attach Subitems to the ListView
listView1.Columns.Add(«Title», 300, HorizontalAlignment.Left);
listView1.Columns.Add(«ID», 70, HorizontalAlignment.Left);
listView1.Columns.Add(«Price», 70, HorizontalAlignment.Left);
listView1.Columns.Add(«Publi-Date», 100, HorizontalAlignment.Left);

// The ListViewItemSorter property allows you to specify the
// object that performs the sorting of items in the ListView.
// You can use the ListViewItemSorter property in combination
// with the Sort method to perform custom sorting.
_lvwItemComparer = new ListViewItemComparer();
this.listView1.ListViewItemSorter = _lvwItemComparer;
>

Loading the ListView with Data from a DataSet

In this example we use a DataSet to load the «Titles» DataTable, which was filled with the Database Table «Titles» in the Pub Database on SQL-Server 2000.

// Load Data from the DataSet into the ListView
private void LoadList()
<
// Get the table from the data set
DataTable dtable = _DataSet.Tables[«Titles»];

// Clear the ListView control
listView1.Items.Clear();

// Display items in the ListView control
for (int i = 0; i < dtable.Rows.Count; i++)
<
DataRow drow = dtable.Rows[i];

// Only row that have not been deleted
if (drow.RowState != DataRowState.Deleted)
<
// Define the list items
ListViewItem lvi = new ListViewItem(drow[«title»].ToString());
lvi.SubItems.Add (drow[«title_id»].ToString());
lvi.SubItems.Add (drow[«price»].ToString());
lvi.SubItems.Add (drow[«pubdate»].ToString());

// Add the list items to the ListView
listView1.Items.Add(lvi);
>
>
>

Handling the ColumnClick Event

In order to determine which set of subitems to sort by, you need to know when the user clicks a column heading for a subitem. To do this, you need to create an event-handling method for the ColumnClick event of the ListView . Place the event-handling method as a member of your form and ensure that it contains a signature similar to the one shown in the following code example.

// Perform Sorting on Column Headers
private void listView1_ColumnClick(
object sender,
System.Windows.Forms.ColumnClickEventArgs e)
<

// Determine if clicked column is already the column that is being sorted.
if (e.Column == _lvwItemComparer.SortColumn)
<
// Reverse the current sort direction for this column.
if (_lvwItemComparer.Order == SortOrder.Ascending)
<
_lvwItemComparer.Order = SortOrder.Descending;
>
else
<
_lvwItemComparer.Order = SortOrder.Ascending;
>
>
else
<
// Set the column number that is to be sorted; default to ascending.
_lvwItemComparer.SortColumn = e.Column;
_lvwItemComparer.Order = SortOrder.Ascending;
>

// Perform the sort with these new sort options.
this.listView1.Sort();
>

Connect the event-handling method to the ListView control by adding code to the constructor of your form, as shown in the following example.

this .listView1.ColumnClick +=
new System.Windows.Forms.ColumnClickEventHandler(
this .listView1_ColumnClick);

Perform custom Sorting

Case Insenstive Sorting

The sorting is performed in a required method of the IComparer interface called Compare . This method takes two objects as parameters, which will contain the two items being compared. When the Sort method is called in the ColumnClick event-handling method of the ListView control, the Sort method uses the ListViewItemComparer object that was defined and assigned to the ListViewItemSorter property and calls its Compare method.

In this example the ListViewItemComparer class uses the Compare method of the CaseInsenstiveComparer class to perform the actual comparison of the items. Note that this method of comparison is not case sensitive («Apple» is considered to be the same as «apple»). Also, note that all of the columns in this example are sorted in a «text» manner.

The Compare method of the CaseInsenstiveComparer p erforms a case-insensitive comparison of two objects of the same type and returns a value indicating whether one is less than, equal to or greater than the other.

public virtual int Compare(
object a,
object b
);

The value returned by the Compare method is passed back to the Sort method, which determines the location in the column of each item being compared. The Sort method makes as many calls to the Compare method as needed to sort all subitems in the selected column.

Add the following class definition to your Form class and ensure that it is nested properly inside your form.

// This class is an implementation of the ‘IComparer’ interface.
public class ListViewItemComparer : IComparer
<
// Specifies the column to be sorted
private int ColumnToSort;

// Specifies the order in which to sort (i.e. ‘Ascending’).
private SortOrder OrderOfSort;

// Case insensitive comparer object
private CaseInsensitiveComparer ObjectCompare;

// Class constructor, initializes various elements
public ListViewItemComparer()
<
// Initialize the column to ‘0’
ColumnToSort = 0;

// Initialize the sort order to ‘none’
OrderOfSort = SortOrder.None;

// Initialize the CaseInsensitiveComparer object
ObjectCompare = new CaseInsensitiveComparer();
>

// This method is inherited from the IComparer interface.
// It compares the two objects passed using a case
// insensitive comparison.
//
// x: First object to be compared
// y: Second object to be compared
//
// The result of the comparison. «0» if equal,
// negative if ‘x’ is less than ‘y’ and
// positive if ‘x’ is greater than ‘y’
public int Compare(object x, object y)
<
int compareResult;
ListViewItem listviewX, listviewY;

// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;

// Case insensitive Compare
compareResult = ObjectCompare.Compare (
listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text
);

// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
<
// Ascending sort is selected, return normal result of compare operation
return compareResult;
>
else if (OrderOfSort == SortOrder.Descending)
<
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
>
else
<
// Return ‘0’ to indicate they are equal
return 0;
>
>

// Gets or sets the number of the column to which to
// apply the sorting operation (Defaults to ‘0’).
public int SortColumn
<
set
<
ColumnToSort = value;
>
get
<
return ColumnToSort;
>
>

// Gets or sets the order of sorting to apply
// (for example, ‘Ascending’ or ‘Descending’).
public SortOrder Order
<
set
<
OrderOfSort = value;
>
get
<
return OrderOfSort;
>
>
>

Simple String Sorting

Another approach is to use the String.Compare method.

When the ListViewItemComparer object is created, it is assigned the index of the column that was clicked. This column index is used to access subitems from the column that needs to be sorted. The subitems are then passed to the String.Compare method, which compares the items and returns one of three results. If the item in the x parameter is less than the item in the y parameter, a value less than zero is returned. If the items are identical, a zero is returned. Finally, if the item in the x parameter is greater than the item in the y parameter, a value greater than zero is returned.

public int Compare(object x, object y)
<
int compareResult;
ListViewItem listviewX, listviewY;

// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;

// Simple String Compare
compareResult = String.Compare (
listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text
);

// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
<
// Ascending sort is selected, return normal result of compare operation
return compareResult;
>
else if (OrderOfSort == SortOrder.Descending)
<
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
>
else
<
// Return ‘0’ to indicate they are equal
return 0;
>
>

Data that is placed into the ListView control as an item is displayed as text and stored as text . This makes it easy to sort using the String.Compare method in an IComparer class. String.Compare sorts both alphabetical characters and numbers. However, certain data types do not sort correctly using String.Compare, such as date and time information. For this reason, the System.DateTime structure has a Compare method just as the String class does. This method can be used to perform the same type of sorting based on chronological order. In this section, you modify only the Compare method to allow for dates to be sorted properly.

public int Compare(object x, object y)
<
int compareResult;
ListViewItem listviewX, listviewY;

// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;

// Determine whether the type being compared is a date type.
try
<
// Parse the two objects passed as a parameter as a DateTime.
System.DateTime firstDate =
DateTime.Parse(listviewX.SubItems[ColumnToSort].Text);
System.DateTime secondDate =
DateTime.Parse(listviewY.SubItems[ColumnToSort].Text);

// Compare the two dates.
compareResult = DateTime.Compare(firstDate, secondDate);
>

// If neither compared object has a valid date format,
// perform a Case Insensitive Sort
catch
<
// Case Insensitive Compare
compareResult = ObjectCompare.Compare (
listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text
);
>

// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
<
// Ascending sort is selected, return normal result of compare operation
return compareResult;
>
else if (OrderOfSort == SortOrder.Descending)
<
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
>
else
<
// Return ‘0’ to indicate they are equal
return 0;
>
>

Читать:
Как удалить people в windows 10 полностью

T he Compare method starts by casting the x and y parameters to DateTime objects. This extraction is performed in a try/catch block to catch exceptions that might occur by forcing the casting of the two items being compared into DateTime objects. If an exception does occur, it signals to the code that the type being converted is not a valid date or time and can be sorted by the String.Compare method. If the two types are dates, they are sorted using the DateTime.Compare method.

Conclusion

The ListView control can provide the ability to display data in a number of ways. It can be used to display single items as well as items that contain subitem information. Using the sorting features provided by the ListView control, you can also enable users to sort items in the ListView control based on those subitems, regardless of the type of data being presented. This ability to sort items and their subitems enables your application to behave in ways that are familiar to users of Microsoft® Windows® Explorer and other applications that provide a ListView display of data and the ability to sort its contents.

Listview c как заполнить таблицу

Элемент ListView представляет список, но с более расширенными возможностями, чем ListBox. В ListView можно отображать сложные данные в различных стобцах, можно задавать данным изображения и пиктограммы.

ListViewItem

Все элементы, как и в других списковых визуальных компонентах, задаются с помощью свойства Items . Но в отличие от ListBox или ComboBox, если мы через панель Свойств откроем окно редактирования элементов ListView:

Каждый отдельный элемент в ListView представляет объект ListViewItem . В окне редактирования элементов мы также можем добавлять и удалять элементы списка. Но кроме того, здесь также мы можем выполнить дополнительную настройку элементов с помощью следующих свойств:

BackColor : фоновый цвет элемента

Checked : если равно true, то данный элемент будет отмечен

Font : шрифт элемента

ForeColor : цвет шрифта

Text : текст элемента

ToolTipText : текст всплывающей подсказки, устанавливаемой для элемента

UseItemStyleForSubItems : если равно true, то стиль элемента будет также использоваться и для всех его подэлементов

Group : задает фоновый цвет элемента

ImageIndex : получает или задает индекс изображения, выводимого для данного элемента

ImageKey : получает или задает индекс изображения для данного элемента

StateImageIndex : получает или задает индекс изображения состояния (например установленного или снятого флажка, указывающего состояние элемента)

SubItems : коллекция подэлементов для данного элемента ListViewItem

Tag : тег элемента

IdentCount : устанавливает отступ от границ ListViewItem до используемого им изображения

Это только те свойства, которые мы можем задать в окне редактирования элементов ListView. Но потом все добавляемые элементы мы сможем увидеть в ListView:

Элемент ListView в Windows Forms

Чтобы добавить к элементам в ListView флажки, кроме задания свойства Checked у каждого отдельного элемента ListViewItem, надо также у свойства CheckBoxes у самого объекта ListView установить значение true .

Изображения элементов

Для добавления элементам изображений у ListView есть несколько свойств:

LargeImageList : задает список ImageList, изображения которого будут использоваться для крупных значков

SmallImageList : задает список ImageList, изображения которого будут использоваться для мелких значков

StateImageList : задает список ImageList, изображения которого будут использоваться для разных состояний

Пусть у нас есть некоторый ImageList с изображениями. Зададим этот ImageList для свойств LargeImageList и SmallImageList.

Тогда при добавлении новых элементов мы можем указать индекс изображение из ImageList, которое будет использоваться элементом:

Тогда в приложении вместе с текстыми метками элементов можно будет увидеть и изображения:

Типы отображений

С помощью свойства View у элемента ListView можно задать тип отображения, который принимает следующие значения:

Details : отображение в виде таблицы

LargeIcon : набор крупных значков (применяется по умолчанию)

SmallIcon : набор мелких значков

При отображении в виде таблицы также надо задать набор столбцов в свойстве Columns у ListView:

В данном случае я указал один столбец, у которого заголовок будет «Страна». Если у элементов ListViewItem были бы подэлементы, то можно было бы также задать и столбцы для подэлементов.

Кроме рассмотренных выше свойств ListView надо еще отметить некоторые. Свойство MultiSelect при установке в true позволяет выделять несколько строк в ListView одновременно.

Свойство Sorting позволяет задать режим сортировки в ListView. По умолчанию оно имеет значение None , но также можно установить сортировку по возрастанию (значение Ascending ) или сортировку по убыванию (значение Descending )

ListView. Практика

Выполним небольшую практическую задачу: выберем все названия файлов из какой-нибудь папки в ListView.

Получение всех файлов в ListView

Во-первых добавим на форму элементы TextBox (для ввода названия папки, файлы которой надо получить), Button (для запуска получения) и ListView.

Чтобы все файлы имели какое-нибудь изображение, добавим на форму ImageList с именем imageList1 и поместим в него какую-нибудь картинку.

Элемент управления ListView

— это исключительно гибкий привязанный к данным элемент управления, отображающий свое содержимое на основе определяемых вами шаблонов. В отличие от Repeater, элемент ListView добавляет высокоуровневые средства, такие как возможность выбора и редактирования, которые работают точно так же, как аналогичные средства GridView. Но в отличие от GridView, элемент ListView не поддерживает модели, основанной на полях, для создания быстрых и простых таблиц с минимальным кодом разметки.

С разных точек зрения ListView можно трактовать либо как более гибкую версию GridView, требующую больше работы, либо как более насыщенную средствами версию простого элемента Repeater, который появился в ASP.NET 1.x.

ListView включает более широкий набор шаблонов, чем GridView. Эти шаблоны перечислены в таблице ниже:

Устанавливает содержимое каждого элемента данных (если вы не используете AlternatingItemTemplate) или каждой нечетной ячейки (если используете)

Применяется в сочетании с ItemTemplate для различного форматирования четных и нечетных строк

Устанавливает содержимое разделителя, размещаемого между элементами

Устанавливает содержимое элемента, выбранного в данный момент. Можно использовать то же содержимое, что и ItemSeparatorTemplate, но с другим форматированием, или же выбрать отображение расширенного вида с дополнительными деталями для выбранного элемента

Устанавливает элементы управления, используемые для элемента в режиме редактирования

Устанавливает элементы управления, используемые для вставки нового элемента

Устанавливает разметку, обертывающую ваш список элементов

Устанавливает разметку, обертывающую каждую группу элементов, если используется средство группирования

Устанавливает содержимое разделителя групп элементов

Устанавливает содержимое, используемое для заполнения пустых значений в последней группе, если применяется группирование. Например, если создаются группы из 5 элементов, а источником данных является коллекция из 13 объектов, то в последней группе будет не хватать 2 элементов

Устанавливает разметку, используемую в случае пустого привязанного объекта данных (т.е. не содержащего записей или объектов)

Наиболее частая причина использования ListView связана с необходимостью создания необычной компоновки, например, чтобы построить таблицу, размещающую более одного элемента в одной строке, или же вообще не использующую обычную табличную компоновку. При построении страницы, предназначенной для отображения больших объемов данных, разработчики на ASP.NET обычно сначала обращаются к GridView, a ListView применяют в более специализированных сценариях.

При отображении некоторых данных в ListView вы следуете тому же процессу, что и в случае элемента GridView, состоящего из столбцов TemplateField. Сначала вы создаете разметку для шаблонов, которые хотите использовать. Как минимум, понадобится шаблон ItemTemplate, который представляет содержимое для каждого элемента. Ниже приведен пример:

При визуализации элемент управления ListView осуществляет проход по привязанным данным и отображает ItemTemplate для каждого элемента. Все это содержимое размещается внутри обычного элемента <span>:

Использование ListView

Часто возникает желание определить шаблон LayoutTemplate для получения большего контроля над расположением элементов. В этом случае список элементов размещается внутри LayoutTemplate. Поведение по умолчанию элемента ListView без LayoutTemplate эквивалентно использованию примерно следующего шаблона LayoutTemplate:

При создании LayoutTemplate для ListView потребуется указать, куда должно быть вставлено содержимое ItemTemplate. Это делается добавлением заполнителя — элемент, который будет дублироваться по одному для каждого элемента привязанных данных. Чтобы обозначить элемент как заполнитель, необходимо просто установить его ID в itemPlaceHolder, как показано выше в примере.

Заполнитель должен быть серверным элементом управления — другими словами, ему нужен атрибут runat=»server». В этом примере используется удобный веб-элемент управления PlaceHolder, но вместо него можно указать серверный элемент <span> или <div>.

Именно шаблон LayoutTemplate придает такую гибкость элементу ListView. Другие элементы управления данными используют шаблоны для содержимого, но не для всей структуры. С помощью LayoutTemplate можете легко адаптировать этот пример для использования таблицы. Например, если вы хотите поместить каждый элемент в отдельную строку (как это делает GridView), для заполнителя элемента необходимо использовать строку таблицы (элемент <tr>):

Теперь каждый элемент может начинать новую строку (с помощью <tr>) и добавлять ячейки по мере необходимости (посредством <td>):

По сравнению с GridView, элемент Listview обладает одним концептуальным недостатком — у него есть только один шаблон для отображения элементов. Чтобы понять, чем это может ограничивать, рассмотрим, что случится, если вы захотите создать многостолбцовое отображение с использованием Listview. Вам нужно будет добавить заголовки столбцов над Listview, а затем определить содержимое всех столбцов в ItemTemplate. Это отлично работает, но приводит к серьезным неудобствам, когда требуется внести кажущиеся тривиальными изменения — вроде изменения последовательности столбцов.

Ради интереса можете создать табличную компоновку, которая была бы невозможной для обычного элемента GridView — такую, которая размещает каждый элемент в отдельном столбце. Концептуально это не сложно. Нужно просто использовать ячейку таблицы (элемент <td>) в качестве заполнителя:

Теперь шаблон LayoutTemplate должен начинаться с дескриптора <td>:

Результат быстро станет трудночитаемым, если отображаемый набор данных окажется достаточно объемным (если не применять разбиение на страницы):

Необычная компоновка с ListView

Группирование

Элемент Listview предоставляет возможность создать несколько более структурированные отображения, которые решают проблему, показанную на рисунке выше. Трюк заключается в применении группирования, которое позволяет указать дополнительный уровень компоновки, используемой для размещения небольших групп записей внутри общей компоновки.

Чтобы воспользоваться группированием, начать следует с установки свойства GroupItemCount, определяющего количество элементов данных в каждой группе:

К сожалению, средство группирования ListView не работает в связке с информацией из привязанных данных. Например, в случае привязки коллекции объектов Product не существует способа разделить их по группам на основе ценовых диапазонов или категорий товаров. Вместо этого группы ListView всегда имеют фиксированный размер. Максимум, что можно — это сделать размер групп настраиваемым пользователем (скажем, применив дополнительный элемент управления, подобный раскрывающемуся списку, из которого пользователь сможет выбирать число для применения в GroupItemCount).

После установки размера группы понадобится изменить LayoutTemplate. Это связано с тем, что общая компоновка более не содержит элементов данных. Вместо этого она содержит группы, которые, в свою очередь, содержат элементы. Чтобы отразить этот факт, вы должны изменить ID с itemPlaceholder на groupPlaceholder. В данном примере каждая группа представляет собой отдельную строку:

Далее необходимо применить шаблон GroupTemplate, который используется в качестве оболочки для каждой группы. GroupTemplate должен предоставлять заполнитель элемента, который находился ранее в LayoutTemplate. В этом примере каждый элемент является отдельной ячейкой:

Теперь ItemTemplate может начинаться с дескриптора <td>, так что каждый элемент — это ячейка внутри строки. В свою очередь, каждая строка — это группа из трех элементов данных в общей таблице. На рисунке ниже показан результат:

При использовании группирования последняя группа может быть заполнена не полностью. Например, в предыдущем примере создается группа из трех элементов. Если количество элементов данных не кратно трем, последняя группа будет неполной. Во многих случаях это не представляет проблемы, но в некоторых возникает сложность — например, если нужно сохранить некоторую структуру или поместить какое-то альтернативное содержимое в таблицу. В такой ситуации можно предоставить новое содержимое, используя EmptyItemTemplate.

Разбиение на страницы

В отличие от других элементов управления, рассматриваемых ранее, ListView не имеет жестко связанного средства разбиения на страницы. Взамен ListView поддерживает другой элемент управления, предназначенный для разбиения на страницы, а именно: DataPager.

Идея, положенная в основу DataPager, заключается в том, что он предлагает простой, согласованный способ использования разбиения на страницы для широкого разнообразия элементов управления. В настоящее время ListView — единственный элемент, поддерживающий DataPager. Однако вполне резонно ожидать, что в будущих версиях DataPager будет работать с другими элементами управления ASP.NET.

Одно из преимуществ DataPager заключается в том, что вам предоставляется гибкость в произвольном размещении его внутри общей компоновки — просто за счет размещения дескриптора в правильном месте LayoutTemplate. Рассмотрим пример совершенно типичного размещения DataPager в нижней части ListView, с кнопками для перемещения вперед и назад на одну страницу либо для быстрого перехода на первую или последнюю страницы:

DataPager также усекает привязанные данные, так что ListView получает соответствующее подмножество этих данных. В текущем примере страницы ограничены тремя элементами. На рисунке показаны кнопки перемещения по страницам:

Русские Блоги

ListView (2) —— C # -WinForm-ListView-таблица отображения данных формата, как отобразить данные в базе данных в ListView, как изменить выбранный элемент

Как отобразить лучший объем данных в базе данных? —form

ListView-Показать данные в табличной форме

Общие атрибуты ListView

HeaderStyle — стиль заголовка столбца в представлении «Сведения».

Нет — не отображать заголовки столбцов

HideSelection — когда элемент управления не имеет фокуса, удалите выделение выбранного элемента.

MultiSelect-Разрешить множественный выбор (True / False).

CheckBoxes-Указывает, отображаются ли флажки рядом с элементом.

FullRowSelect — указывает, когда элемент выбран, выделены ли все его дочерние элементы вместе с элементом.

GridLines-Отображение линий сетки вокруг предметов и дочерних элементов. Отображается только в представлении «Детали».

Вид — Выберите один из разных видов, которые могут отображать элементы.

1. Установите заголовок столбца таблицы Columns, добавьте 5 столбцов, установите текст и при необходимости установите свойства TextAlign и Width.

(Свойство TextAlign первого столбца может быть только левым, а не центрированным. Как центрировать первый столбец? Данные отображаются из второго столбца, так что ширина первого столбца равна 0)

2. Установите для свойства View значение Details, и в это время может отображаться имя столбца.

В-третьих, отобразить свойства коллекции Data-Items в свойствах ListView

Нажмите кнопку <Добавить>, чтобы добавить целую строку, где текстовое значение является значением первого столбца. Как добавить другие данные в строке? Существует свойство коллекции SubItems, когда вы открываете Предметы, добавляете столбцы и устанавливаете текстовое значение

Как отобразить данные в базе данных в ListView? (Ли Сянс lxc)

Как отобразить выбранные элементы?

На рисунке выше показаны как выбранные строки, так и выбранные флажки. Как отобразить имя пользователя и пол выбранного элемента, нажав <Получить параметры>?

Похожие статьи