Reputation: 3888
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
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:
ListView
.ListView
from your state objectTo 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
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