C# – How to get a list of column headers of a listview based on displayindex

c++listview

If the AllowReorder column of a listview is set to true, how do I get a string list of the columnheader texts based on their displayindex at runtime? listview.Columns only returns columns in the original order.

Best Solution

C# 2.0? Or C# 3.0? The LINQ answer (C# 3.0, with either .NET 3.5 or .NET 2.0/3.0 with LINQBridge) is a lot easier ;-p

i.e.

    var names = (from col in listView.Columns.Cast<ColumnHeader>()
                 orderby col.DisplayIndex
                 select col.Text).ToList();

vs:

        List<ColumnHeader> cols = new List<ColumnHeader>();
        // populate
        foreach (ColumnHeader column in listView.Columns) {
            cols.Add(column);
        }
        // sort
        cols.Sort(delegate(ColumnHeader x, ColumnHeader y) {
            return x.DisplayIndex.CompareTo(y.DisplayIndex);
        });
        // project
        List<string> names = cols.ConvertAll<string>(delegate(ColumnHeader x) {
            return x.Text;
        });

Either way, that gives you a List<string> of the column header text values.