views:

1376

answers:

3

I have a "settings file" in my Winforms application called Settings.settings with a partial class for custom methods, etc. Is there a way to load / save dynamic settings based on arbitrary keys?

For example, I have some ListViews in my application in which I want to save / load the column widths; Instead of creating a width setting for each column for each list view I would like a simple method to load / save the widths automatically.

Below is an example of the save method I have tried:

internal sealed partial class Settings
{
 public void SetListViewColumnWidths(ListView listView)
 {
  String baseKey = listView.Name;
  foreach (ColumnHeader h in listView.Columns)
  {
   String key = String.Format("{0}-{1}", baseKey, h.Index);
   this[key] = h.Width;
  }
 }
}

When running that code I get the error "The settings property 'TestsListView-0' was not found." Is there something I am missing?

A: 

I think the error

The settings property 'key' was not found.

occurs because the 'key' value does not exist in your settings file (fairly self-explanatory).

As far as I am aware, you can't add settings values programmatically, you might need to investigate adding all of the settings you need to the file after all, although once they are there, I think you'll be able to use the sort of code you've given to save changes.

To Save changes, you'll need to make sure they are 'User' settings, not 'Application'.

The Settings file is quite simple XML, so you might be able to attack the problem by writing the XML directly to the file, but I've never done it, so can't be sure it would work, or necessarily recommend that approach.

http://msdn.microsoft.com/en-us/library/cftf714c.aspx is the MSDN link to start with.

James Osborn
A: 

You can do Settings.Save() or similar on user settings, but note that such settings would NOT get persisted to the xxx.exe.config file in your app directory as you'd expect. They actually go somewhere deep inside the user folder (search your drive for xxx.exe.config to find it). Next time that you manually change xxx.exe.config in your app directory, the change will mysteriously not apply (the system is still using the saved one from the user directory).

dbkk
+1  A: 
orj