Friday, March 4, 2011

How to get a list of column headers of a listview based on displayindex?

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.

From stackoverflow
  • 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.

0 comments:

Post a Comment