Trevor Balcom
Trevor Balcom

Reputation: 3888

Persisting ListView column order

Is there a best practice regarding saving/loading the state of the columns of a ListView control? I would like to remember the order and size of columns so the ListView always remains as the user has customized it. Is there some built-in way to serialize/deserialize the ListView column width and order? I am having trouble finding the answer on Google.

Upvotes: 2

Views: 1851

Answers (2)

Grammarian
Grammarian

Reputation: 6882

ObjectListView -- an open source wrapper around a .NET WinForms ListView -- has methods to persist the state of the ListView. Have a look at SaveState() and RestoreState() methods.

The general strategy is:

  1. Create an object that holds the state of the ListView.
  2. Serialize that object using a formatter to series of bytes
  3. Persist that series of bytes
  4. When restoring, use the formatter again to inflate the bytes into your state object.
  5. Restore the state of the ListView from your state object

To serialize your state object, you'll need something like this:

using (MemoryStream ms = new MemoryStream()) {
    BinaryFormatter serializer = new BinaryFormatter();
    serializer.AssemblyFormat = FormatterAssemblyStyle.Simple;
    serializer.Serialize(ms, listViewState);
    return ms.ToArray();
}

To restore your state:

using (MemoryStream ms = new MemoryStream(state)) {
    BinaryFormatter deserializer = new BinaryFormatter();
    ListViewState listViewState;
    try {
        listViewState = deserializer.Deserialize(ms) as ListViewState;
    } catch (System.Runtime.Serialization.SerializationException) {
        return false;
    }
    // Restore state here
}

The only tricky bit is restoring the order of the columns. DisplayIndex is notoriously finicky.

Upvotes: 0

John Arlen
John Arlen

Reputation: 6689

There is no built-in way. Extract the data and persist it in a way that makes sense for your application.

Configuration settings is usually the easiest.

Best practice to save application settings in a Windows Forms Application

Upvotes: 1

Related Questions