1
\$\begingroup\$

Here is an "enhanced" Listview class. You can just add it your project and you're good to go. Most of the code came from here and there. It's not perfect by any means, so any input is appreciated.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Globalization;

namespace ChangeThisNamespace
{
    partial class EnhancedListView
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // EnhancedListView
            // 
            this.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.EnhancedListView_ColumnClick);
            this.ResumeLayout(false);
        }

        #endregion
    }
}

namespace ChangeThisNamespace
{
    public partial class EnhancedListView : ListView
    {
        enum lvEvents : uint
        {
           ItemAdded = 0x104D,
           ItemRemoved = 0x1008
        }
        private ListViewColumnSorter lvwColumnSorter;

        public event EventHandler ItemAdded;
        public event EventHandler ItemRemoved;
        /// <summary>
        /// Sets or Gets alternate color for the listview rows.
        /// </summary>
        public Color AlternateColor { get; set; }
        /// <summary>
        /// Sets or Gets DateTimeFormat for sorting columns that contain DateTime.
        /// </summary>
        public string DateTimeFormat { set; get; }
        public EnhancedListView()
        {
            AlternateColor = Color.Empty;
            lvwColumnSorter = new ListViewColumnSorter();
            this.ListViewItemSorter = lvwColumnSorter;
            ItemAdded += ItemAddedToLV;
            ItemRemoved += ItemRemovedFromLV;
            //Activate double buffering
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            //Enable the OnNotifyMessage event so we get a chance to filter out 
            // Windows messages before they get to the form's WndProc
            this.SetStyle(ControlStyles.EnableNotifyMessage, true);
            InitializeComponent();
        }
        protected override void InitLayout()
        {
            lvwColumnSorter.timeFormat = DateTimeFormat;
            base.InitLayout();
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            lvwColumnSorter.timeFormat = DateTimeFormat;
            base.OnPaint(e);
        }
        protected override void OnNotifyMessage(Message m)
        {
            //Filter out the WM_ERASEBKGND message
            if (m.Msg != 0x14)
            {
                base.OnNotifyMessage(m);
            }
        }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            switch ((lvEvents)m.Msg)
            {
                case lvEvents.ItemAdded:
                    if (ItemAdded != null)
                    {
                        ItemAdded(this, null);
                    }
                    break;
                case lvEvents.ItemRemoved:
                    if (ItemRemoved != null)
                    {
                        ItemRemoved(this, null);
                    }
                    break;

                default:
                    break;
            }
        }
        public void SetAlternateColor()
        {
            try
            {
                if (!AlternateColor.IsEmpty && this.Items.Count != 0)
                {
                    if (this.Items.Count > 1)
                    {
                        for (int ix = 0; ix < this.Items.Count; ++ix)
                        {
                            var item = this.Items[ix];
                            item.BackColor = (ix % 2 == 0) ? AlternateColor : Color.White;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
        void ItemAddedToLV(object sender, EventArgs e)
        {
            SetAlternateColor();
        }
        void ItemRemovedFromLV(object sender, EventArgs e)
        {
            MessageBox.Show("Removed");
            SetAlternateColor();
        }
        private void EnhancedListView_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (this.Items.Count != 0)
            {
                // 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.
                    if (lvwColumnSorter.Order == System.Windows.Forms.SortOrder.Ascending)
                    {
                        lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Descending;
                    }
                    else
                    {
                        lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Ascending;
                    }
                }
                else
                {
                    // Set the column number that is to be sorted; default to ascending.
                    lvwColumnSorter.SortColumn = e.Column;
                    lvwColumnSorter.Order = System.Windows.Forms.SortOrder.Ascending;
                }

                // Perform the sort with these new sort options.
                this.Sort();
                SetAlternateColor();
            }
        }

    }

    public class ListViewColumnSorter : IComparer
    {
        public string timeFormat { set; get; } // = "HH:mm:ss - dd-MM-yyyy";
        //private string dtFormat;
        /// <summary>
        /// Specifies the column to be sorted
        /// </summary>
        private int columnToSort;
        /// <summary>
        /// Specifies the order in which to sort (i.e. 'Ascending').
        /// </summary>
        private SortOrder orderOfSort;
        /// <summary>
        /// Case insensitive comparer object
        /// </summary>
        private CaseInsensitiveComparer objectCompare;
        //private CaseInsensitiveComparer xNumber;
        /// <summary>
        /// Class constructor.  Initializes various elements
        /// </summary>
        public ListViewColumnSorter()
        {
            // Initialize the column to '0'
            columnToSort = 0;
            // Initialize the sort order to 'none'
            orderOfSort = SortOrder.None;
            // Initialize the CaseInsensitiveComparer object
            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)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;
            // Cast the objects to be compared to ListViewItem objects
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            // Compare the two items
            int valueX;
            int valueY;
            string txtValueX = listviewX.SubItems[columnToSort].Text;
            string txtValueY = listviewY.SubItems[columnToSort].Text;

            double xNumber, yNumber;
            bool parsed = double.TryParse(txtValueX, out xNumber);
            parsed = parsed && double.TryParse(txtValueY, out yNumber);
            if (parsed)
            {
                compareResult = objectCompare.Compare((int.TryParse(listviewX.SubItems[columnToSort].Text, out valueX) ? valueX : 0), (int.TryParse(listviewY.SubItems[columnToSort].Text, out valueY) ? valueY : 0));
            }
            else
            {
                compareResult = objectCompare.Compare(listviewX.SubItems[columnToSort].Text, listviewY.SubItems[columnToSort].Text);
            }
            DateTime dateX;
            DateTime dateY;
            if (timeFormat != "" && timeFormat != null)
            {
                if (
                        DateTime.TryParseExact(listviewX.SubItems[columnToSort].Text, timeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateX)
                        && DateTime.TryParseExact(listviewY.SubItems[columnToSort].Text, timeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateY)
                   )
                {
                    compareResult = objectCompare.Compare(dateX, dateY);
                }
            }

            // Calculate correct return value based on object comparison
            if (orderOfSort == SortOrder.Ascending)
            {
                // Ascending sort is selected, return normal result of compare operation
                return compareResult;
            }
            else if (orderOfSort == 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
        {
            set { columnToSort = value; }
            get { return columnToSort; }
        }

        /// <summary>
        /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
        /// </summary>
        public SortOrder Order
        {
            set { orderOfSort = value; }
            get { return orderOfSort; }
        }

    }

}
\$\endgroup\$
2
  • \$\begingroup\$ why two column sorter references? lvwColumnSorter = new ListViewColumnSorter();this.ListViewItemSorter = lvwColumnSorter; why not just set thisListViewColumnSorter = new ListViewColumnSorter()? \$\endgroup\$ Commented Feb 23, 2014 at 22:58
  • \$\begingroup\$ Thanks for your feedback, I tried that out and it does not work for some weird reason, unless I do it that way. Thanks again. \$\endgroup\$
    – NetInfo
    Commented Feb 27, 2014 at 0:04

1 Answer 1

3
\$\begingroup\$

Random observations...

Why is the ListViewColumnSorter class partial?

Compare

I think the code could get clearer here. First thing I'd address, I'd declare a int result; and return only once.

Then the declarations and casting:

ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;

Not sure what this is buying you. Wouldn't it be more readable like this?

var listViewX = x as ListViewItem;
var listViewY = y as ListViewItem;

if (listViewX == null || listViewY == null) throw new ArgumentException();

Throwing an ArgumentException (perhaps with a more detailed message) would be less surprising than the InvalidCastException thrown by the explicit cast if x or y isn't a ListViewItem.

The naming of the variables is confusing. You have int valueX and then string xValue:

// Compare the two items
int valueX;
int valueY;
string xValue = listviewX.SubItems[ColumnToSort].Text;
string yValue = listviewY.SubItems[ColumnToSort].Text;

If xValue is the text value of the column to sort for ListViewX, wouldn't textValueX and textValueY be more descriptive names?


Instead of timeFormat != "" you should be testing for !String.IsNullOrEmpty(timeFormat).


Private fields

Your private fields don't follow C# naming conventions:

private SortOrder OrderOfSort;

Should be orderOfSort or _orderOfSort... although I don't see a reason for it not to be _sortOrder or sortOrder.

#region

#region is usually a code smell in itself. It's not so bad in this case, because it's wrapping an entire class, but then why wrap a class in a #region anyway? Move the class into its own file!


switch (m.Msg)

I think I'd try to convert that to an enum with the values you're expecting, so as to eliminate the cryptic 0x1007, 0x104D and 0x1008 "magic numbers", making your cases look like:

case WndProcMessage.ListViewItemAddedA:
case WndProcMessage.ListViewItemAddedW:
case WndProcMessage.ListViewItemRemoved:

Swallowed Exceptions

SetAlternateColor has this catch block:

        catch (Exception)
        {
        }

Are you expecting a particular exception type? This code is swallowing all exceptions, which is bad. At least output it somewhere (log, debug output, whatever):

        catch (Exception exception)
        {
             Console.WriteLine(exception);
        }
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for your detailed feedback, 1.The partial class was done by mistake. 2. That didn't work for some reason. 3. Changed the variable names as you pointed it out. 4. Again changed the names. 5. Created enums as pointed out. 6. I've done it like that for the code just to try and not to return any exceptions. Thanks again, I really do appreciate it. \$\endgroup\$
    – NetInfo
    Commented Feb 27, 2014 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.