Here is a solution offered by Bharat Patel of Microsoft in the microsoft.public.dotnet.languages.csharp newgroup. The attached solution contains both C# and VB.NET projects.
The solution use Interop with the LVM_GETSUBITEMRECT window’s message to loop through each subitem’s bounds rectangle until it finds the one that contains the specified mouse click point.
You create a class the implements the IComparer interface. This interface has a single method that accepts two objects, and returns positive integers if the first object is larger than the second, negative integers if the first object is less than the second object, and returns zero if they are the same. Once you have this class, then you handle the listview’s ColumnClick event to set the property ListViewItemSorter to point to an instance of this class. You can download a sample project. Here are some snippets.
publicclassSorterClass : IComparer
{
privateint _colNum = 0;
publicSorterClass(int colNum)
{
_colNum = colNum;
}
//this routine should return -1 if xy and 0 if x==y.// for our sample we’ll just use string comparisonpublicintCompare(object x, object y)
{
System.Windows.Forms.ListViewItem item1 = (System.Windows.Forms.ListViewItem) x;
System.Windows.Forms.ListViewItem item2 = (System.Windows.Forms.ListViewItem) y;
if(int.Parse(item1.SubItems[_colNum].Text) < int.Parse(item2.SubItems[_colNum].Text))
return-1;
elseif(int.Parse(item1.SubItems[_colNum].Text) > int.Parse(item2.SubItems[_colNum].Text))
return1;
elsereturn0;
}
}
//usage...privatevoidlistView1_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
{
//don’t sort col 0if(e.Column > 0)
{
SorterClass sc = new SorterClass(e.Column);
listView1.ListViewItemSorter = sc;
}
}
Carlos Perez explains how to do this in an article and a sample on codeproject.com. In this sample, he does an owner-drawn listview so he can implement custom sorting with a column header that contains a up/down icon to indicate the sorted column and order.
Make sure the item’s UseItemStyleForSubItems property is set to false.
ListViewItem item1 = new ListViewItem('item1',0);
//this line makes things work
item1.UseItemStyleForSubItems = false;
//set fore & back color of next sub item
item1.SubItems.Add('1', Color.Black, Color.LightGreen, Font);
item1.SubItems.Add('44');
item1.SubItems.Add('3');
//As long as UseItemStyleForSubItems is false, you can later set the colors with code such as
item1.SubItems[2].BackColor = Color.Pink;
Make sure the ListView has focus when you set the Selected property. For example, if this code is in the click handler for a button, this button will have the focus, and the selection in the list will fail. Just set the focus back to the list before you set the Selected property.