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.
Asked
Active
Viewed 1,815 times
2 Answers
1
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

Community
- 1
- 1

John Arlen
- 6,539
- 2
- 33
- 42
0
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:
- Create an object that holds the state of the
ListView
. - Serialize that object using a formatter to series of bytes
- Persist that series of bytes
- When restoring, use the formatter again to inflate the bytes into your state object.
- 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.

Grammarian
- 6,774
- 1
- 18
- 32