Skip to content

Instantly share code, notes, and snippets.

@sinairv
Created May 14, 2012 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinairv/2693729 to your computer and use it in GitHub Desktop.
Save sinairv/2693729 to your computer and use it in GitHub Desktop.
Dealing with ListView control, in the details mode
// taken from: http://msdn.microsoft.com/en-us/library/ms996467.aspx
using System.Collections;
using System.Windows.Forms;
namespace ListViewControlling
{
/// <summary>
/// This class is an implementation of the 'IComparer' interface.
/// </summary>
public class ListViewColumnSorter : IComparer
{
/// <summary>
/// Case insensitive comparer object
/// </summary>
private readonly CaseInsensitiveComparer m_objectCompare;
/// <summary>
/// Class constructor. Initializes various elements
/// </summary>
public ListViewColumnSorter()
{
// Initialize the column to '0'
SortColumn = 0;
// Initialize the sort order to 'none'
Order = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
m_objectCompare = new CaseInsensitiveComparer();
}
/// <summary>
/// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison.
/// </summary>
/// <param name="x">First object to be compared</param>
/// <param name="y">Second object to be compared</param>
/// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
public int Compare(object x, object y)
{
// Cast the objects to be compared to ListViewItem objects
var listviewX = (ListViewItem)x;
var listviewY = (ListViewItem)y;
// Compare the two items
int compareResult = m_objectCompare.Compare(listviewX.SubItems[SortColumn].Text, listviewY.SubItems[SortColumn].Text);
// Calculate correct return value based on object comparison
if (Order == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (Order == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
}
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn { get; set; }
/// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary>
public SortOrder Order { get; set; }
}
}
using System;
using System.Text;
using System.Windows.Forms;
namespace ListViewControlling
{
public class ListViewUtils
{
public static void InitListView(ListView lstView)
{
lstView.Items.Clear();
lstView.Columns.Clear();
lstView.View = View.Details;
lstView.Tag = new StringBuilder();
// Create an instance of a ListView column sorter and assign it
// to the ListView control.
var lvwColumnSorter = new ListViewColumnSorter();
lstView.ListViewItemSorter = lvwColumnSorter;
lstView.ColumnClick -= ListViewColumnClick;
lstView.ColumnClick += ListViewColumnClick;
lstView.KeyUp -= ListViewKeyUp;
lstView.KeyUp += ListViewKeyUp;
}
public static void AppendToListView(ListView lstView, params string[] cols)
{
var sb = lstView.Tag as StringBuilder;
if (sb == null)
throw new Exception("The tag of the ListView object must be an instance of StringBuilder!");
const int colLength = 15;
if (lstView.Columns.Count <= 0)
{
foreach (var col in cols)
{
lstView.Columns.Add(col, col);
}
sb.AppendLine(CreateCols(colLength, cols));
sb.AppendLine("-----------------------------------------------------");
}
else
{
if (cols.Length > lstView.Columns.Count)
{
for (int i = 0; i < cols.Length - lstView.Columns.Count; i++)
{
lstView.Columns.Add("Unknown", "");
}
}
lstView.Items.Add(new ListViewItem(cols));
sb.AppendLine(CreateCols(colLength, cols));
}
}
private static void ListViewKeyUp(object sender, KeyEventArgs e)
{
// check if Ctrl + C or Ctrl + Insert is pressed
if (e.Control && (e.KeyCode == Keys.C || e.KeyCode == Keys.Insert))
{
var lst = sender as ListView;
if (lst == null)
return;
var sb = lst.Tag as StringBuilder;
if (sb == null)
return;
Clipboard.SetText(sb.ToString(), TextDataFormat.UnicodeText);
}
}
private static void ListViewColumnClick(object sender, ColumnClickEventArgs e)
{
var lst = sender as ListView;
if (lst == null)
return;
var lvwColumnSorter = lst.ListViewItemSorter as ListViewColumnSorter;
if (lvwColumnSorter == null)
return;
// Determine if clicked column is already the column that is being sorted.
if (e.Column == lvwColumnSorter.SortColumn)
{
// Reverse the current sort direction for this column.
lvwColumnSorter.Order = lvwColumnSorter.Order == SortOrder.Ascending ?
SortOrder.Descending : SortOrder.Ascending;
}
else
{
// Set the column number that is to be sorted; default to ascending.
lvwColumnSorter.SortColumn = e.Column;
lvwColumnSorter.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
lst.Sort();
}
private static string CreateCols(int colLength, params string[] cols)
{
var sb = new StringBuilder();
string fmt = "{0,-" + colLength + "}";
foreach (var col in cols)
{
sb.AppendFormat(fmt, col);
}
return sb.ToString();
}
}
}
var lstCults = CultureInfo.GetCultures(CultureTypes.AllCultures).ToList();
lstCults.Sort((v1, v2) => v1.Name.CompareTo(v2.Name));
var today = DateTime.Today;
ListViewUtils.InitListView(listView1);
ListViewUtils.AppendToListView(listView1, "Name", "Native-Name", "Y");
foreach (var cult in lstCults)
{
ListViewUtils.AppendToListView(listView1, cult.Name, cult.NativeName,
cult.Calendar.GetYear(today).ToString(),
cult.DateTimeFormat.FullDateTimePattern);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment