可排序的ListView

代码
public partial class ListViewEx : ListView
{
private bool flag = false;

public ListViewEx()
{
InitializeComponent();
}

public ListViewEx(IContainer container)
{
container.Add(
this);

InitializeComponent();
}

protected override void OnColumnClick(ColumnClickEventArgs e)
{
base.OnColumnClick(e);
this.ListViewItemSorter = new ListViewItemComparer(e.Column,flag);
if (flag) flag = false;
else flag = true;
}
}


class ListViewItemComparer : System.Collections.IComparer
{
private int _column;
private bool _flag;
public ListViewItemComparer(int column,bool flag)
{
this._column = column;
this._flag = flag;
}

#region IComparer Members

public int Compare(object x, object y)
{
int t= (string.Compare(((ListViewItem)x).SubItems[_column].Text, ((ListViewItem)y).SubItems[_column].Text));
if (_flag) { t = -t; }
return t;
}
#endregion
}


/////////////////////////
this.FullRowSelect = true;
this.GridLines = true;
this.View = System.Windows.Forms.View.Details;


 

 

        void InitListView()
        {          

            int x = 20;
            int y = 200;
           
            this.listViewEx.BeginUpdate();
            this.listViewEx.Clear();

            DateTime d1 = DateTime.Now;

            for (int i = 0; i < x; i++)
            {
                this.listViewEx.Columns.Add(i.ToString(), 8 * 12, HorizontalAlignment.Center);
            }
            ListViewItem lv=null;           
            for (int i = 0; i < y; i++)
            {
                lv = new ListViewItem(i.ToString());
              
                lv.Text = i.ToString();              
                for (int j = 1; j < x; j++)
                {                    
                    lv.SubItems.Add(i.ToString() + ", " + j.ToString());
                }
                this.listViewEx.Items.Add(lv);
            }
            TimeSpan ts1 = DateTime.Now - d1;
            this.Text = ts1.ToString();
            this.listViewEx.EndUpdate();

        }

posted @ 2010-06-04 18:09  庚武  Views(220)  Comments(0Edit  收藏  举报