CustomListView: ListView que permite reordenar los datos (AllowSorting)
This commit is contained in:
97
ServerExplorer/Controls/CustomListView.cs
Normal file
97
ServerExplorer/Controls/CustomListView.cs
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user