C#使用数据集填充ListView,并通过列标题执行排序

C#使用数据集填充ListView,并通过列标题执行排序, 当您使用ListView控件时,您可能需要根据特定列对其内容进行排序。当您查看硬盘上的文件夹的内容时,Windows资源管理器程序中会出现此类功能的一个示例。在详细信息视图中,Windows资源管理器显示有关该文件夹中的文件的信息 例如,您会看到文件名,文件大小,文件类型以及文件被修改的日期。

C#使用数据集填充ListView

本文将展示如何用数据加载到DataSet填充ListView控件。您可以使用DataSet将其绑定到网格控件以显示查询的输出,但控件的数据绑定并不总是访问数据的理想方法(您可能会遇到DataBinding问题)。DataSet在客户端系统内存中维护整个结果集的副本,以防需要对行进行更改。而不是使用绑定的网格和数据集,我们可以使用列表视图控件与视图设置为详细模式,并填充数据从数据集。

排序ListView

当您使用ListView控件时,您可能需要根据特定列对其内容进行排序。当您查看硬盘上的文件夹的内容时,Windows资源管理器程序中会出现此类功能的一个示例。在详细信息视图中,Windows资源管理器显示有关该文件夹中的文件的信息 例如,您会看到文件名,文件大小,文件类型以及文件被修改的日期。当您单击某个列标题时,该列表将按照该列的升序进行排序。当再次单击相同的列标题时,该列按降序排列。

ListView控件

本文中的示例定义了一个从IComparer接口继承的类 。此外,此示例使用比较 方法的的CaseInsenstiveComparer类来执行的项目的实际比较。请注意,这种比较方法不区分大小写(“苹果”被认为是“苹果”)。另外,请注意,本例中的所有列都以“文本”方式排序。

C#使用数据集填充ListView,并通过列标题执行排序
C#使用数据集填充ListView,并通过列标题执行排序

介绍

ListView控件是显示XML文件或数据库中的文件系统信息和数据的好方法。ListView控件通常用于显示表示项目的图形图标以及项目文本。此外,ListView控件可用于显示有关子项目中项目的其他信息。例如,如果ListView控件正在显示文件列表,则可以配置ListView控件以显示细节(如文件大小和属性)为子项。要在ListView控件中显示子项信息,必须将View属性设置为View.Details。另外,你必须创建 ColumnHeader对象并将它们分配给ListView控件的Columns属性。一旦设置了这些属性,项目就会以与DataGrid控件类似的行和列格式显示。以这种方式显示项目的能力使得ListView控件成为显示来自任何类型的数据源的数据的快速而简单的解决方案。

通过使用ListView 的Sorting属性来提供对ListView控件的排序。这使您可以定义应用于项目的排序类型。如果您只想按项目排序,这是一项很棒的功能。如果要按子项排序,则必须使用ListView控件自定义排序功能。本文将演示如何在ListView控件中执行自定义排序以及如何在排序时处理特殊的数据类型条件。

ListView控件的自定义排序功能

ListView控件提供的功能使您能够使用排序属性提供的排序以外的排序。当ListView控件使用Sorting属性对项目进行排序时,它使用实现 System.Collections.IComparer接口的类。这个类提供了用于排序每个项目的排序功能。为了按子项排序,您必须创建自己的实现IComparer的类接口,接着实现ListView控件所需的排序。该类是用一个构造函数来定义的,该构造函数指定ListView控件排序的列。一旦创建了这个类,通常作为表单的嵌套类,就创建了这个类的一个实例,并将其分配给 ListView的ListViewItemSorter属性。这标识了ListView控件在调用Sort方法时将使用的自定义排序类。Sort方法执行ListView项目的实际排序。

初始化控制

首先,创建一个ListView控件的实例并将其添加到一个表单。控件在窗体上后,使用Items属性将项目添加到ListView控件。你可以添加尽可能多的项目,你想要的; 只要确保每个项目的文本是唯一的。当您创建的项目,加小号 ubitems每个。下表是如何在ListView控件中查看此信息的示例。

项目分项1分项2
 5
C#使用数据集填充ListView,并通过列标题执行排序
// 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;
}

C#使用数据集填充ListView,并通过列标题执行排序

使用DataSet中的数据加载ListView

在这个例子中,我们使用一个DataSet来加载“标题”数据表,该数据表填充了SQL Server 2000 Pub数据库中的数据库表“标题”。

// 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);
}
}
}

C#使用数据集填充ListView,并通过列标题执行排序

处理 ColumnClick 事件

为了确定要排序的子集项,您需要知道用户何时单击子项的列标题。为此,您需要为ListViewColumnClick事件创建一个事件处理方法。将事件处理方法作为表单的成员,并确保它包含一个类似于下面的代码示例中显示的签名。

// 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();
}

C#使用数据集填充ListView,并通过列标题执行排序

通过将代码添加到窗体的构造函数,将事件处理方法连接到ListView控件,如下例所示。

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

C#使用数据集填充ListView,并通过列标题执行排序

执行自定义排序

案例 Insenstive 排序

排序是在名为CompareIComparer接口 的必需方法中执行的。这个方法以两个对象作为参数,它们将包含两个被比较的项目。在ListView控件的ColumnClick事件处理方法中调用Sort方法时,Sort方法使用已定义并分配给ListViewItemSorter 属性ListViewItemComparer对象, 并调用其Compare方法。

在这个例子中  ,ListViewItemComparer类使用CaseInsenstiveComparer类的Compare方法 来执行项目的实际比较。请注意,这种比较方法不区分大小写(“苹果”被认为是“苹果”)。另外,请注意,本例中的所有列都以“文本”方式排序。

 比较的方法 CaseInsenstiveComparer p erforms同一类型的两个对象的区分大小写的比较,并返回指示一个是否小于,等于或大于另一个的值。

将下面的类定义添加到您的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;
}
}
}

C#使用数据集填充ListView,并通过列标题执行排序

简单的字符串排序

另一种方法是使用String.Compare 方法。

当ListViewItemComparer对象被创建时,它被分配了被点击的列的索引。此列索引用于从需要排序的列中访问子项目。子项目然后传递给String.Compare方法,该方法比较项目并返回三个结果之一。如果x参数中的项目小于y参数中的项目,则返回小于零的值。如果项目相同,则返回零。最后,如果x参数中的项大于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;

// 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;
}
}

C#使用数据集填充ListView,并通过列标题执行排序

C#使用数据集填充ListView,并通过列标题执行排序 1

排序日期

作为项目放入ListView控件的数据显示为文本并以文本形式存储。这使得使用IComparer类中的String.Compare方法很容易进行排序。String.Compare对字母和数字进行排序。但是,某些数据类型不能使用String.Compare正确排序,如日期和时间信息。由于这个原因,System.DateTime结构与String类一样有一个Compare方法。这种方法可以用来根据时间顺序执行相同类型的排序。在本节中,您只修改了比较方法,以便日期能够正确排序。

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;
}
}

Ť比较法铸造的开始xy参数的DateTime对象。此提取在try / catch块中执行,以通过强制将正在比较的两个项目转换为DateTime对象来发生异常。如果发生异常,则向代码发出信号,表明正在转换的类型不是有效的日期或时间,可以使用String.Compare方法进行排序。如果这两种类型是日期,则使用DateTime.Compare方法对它们进行排序。

结论

WinForm的ListView控件可以提供以许多方式来显示数据的能力。它可以用来显示单个项目以及包含子项目信息的项目。通过使用ListView控件提供的排序功能,还可以使用户能够根据这些子项对ListView控件中的项进行排序,而不管呈现的数据的类型如何。这种对项目及其子项进行排序的功能使您的应用程序能够以Windows资源管理器的方式运行,而其他应用程序则提供数据的 ListView显示和排序其内容的能力。

猜你喜欢

本站最新优惠

Namesilo优惠:新用户省 $1 域名注册-优惠码:45D%UYTcxYuCloZ 国外最便宜域名!点击了解更多

特别优惠:免费赠送 $100 Vultr主机-限时优惠!英文站必备海外服务器!点击了解更多

VPS优惠:搬瓦工优惠码:BWH3OGRI2BMW 最高省5.83%打开外面世界的一款主机点击了解更多

加入电报群

【江湖人士】(jhrs.com)原创文章,作者:江小编,如若转载,请注明出处:https://jhrs.com/2018/2600.html

扫码加入电报群,让你获得国外网赚一手信息。

文章标题:C#使用数据集填充ListView,并通过列标题执行排序

(0)
江小编的头像江小编
上一篇 2017-12-31 11:58
下一篇 2018-01-05 11:08

热门推荐

发表回复

登录后才能评论
畅访海外网站,外贸/外企/科技工作者专用工具,无缝体验真实的互联网,解锁LinkedIn访问
$19.95 /年
直达官网