CustomListView: ListView que permite reordenar los datos (AllowSorting)

This commit is contained in:
2013-11-22 00:50:24 +01:00
parent 4f7664794f
commit 12e67b0e25
8 changed files with 182 additions and 85 deletions

View File

@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Collections;
namespace ServerExplorer.Controls
{
[DefaultProperty("Items")]
[DefaultEvent("SelectedIndexChanged")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[Docking(DockingBehavior.Ask)]
public class CustomListView : ListView
{
#region Declarations
ListViewItemComparer itemComparer = new ListViewItemComparer();
#endregion
#region Properties
private bool allowSorting = false;
public bool AllowSorting
{
get { return allowSorting; }
set { allowSorting = value; }
}
#endregion
#region Control life cicle
public CustomListView()
{
ColumnClick += CustomListView_ColumnClick;
}
#endregion
#region Events
private void CustomListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (!allowSorting) { return; }
itemComparer.SetColumn(e.Column);
ListViewItemSorter = itemComparer;
Sort();
}
#endregion
}
#region ListViewItemComparer
class ListViewItemComparer : IComparer
{
private int col;
private bool ascending;
public void SetColumn(int col)
{
if (this.col == col)
{
ascending = ascending ? false : true;
}
else
{
this.col = col;
ascending = true;
}
}
public int Compare(object x, object y)
{
int returnVal = -1;
if (ascending)
{
returnVal = String.Compare(
((ListViewItem)x).SubItems[col].Text,
((ListViewItem)y).SubItems[col].Text);
}
else
{
returnVal = String.Compare(
((ListViewItem)y).SubItems[col].Text,
((ListViewItem)x).SubItems[col].Text);
}
return returnVal;
}
}
#endregion
}