views:

25

answers:

2

I need simple way to persist and edit a set of string pairs in my application. I believe that DataGridView with two culmns can help me with viewing and editing, and I was hoping to use application settings instead of database to store data (maybe a DataSet as setting type). I just can't put all that together. Is there a way?

A: 

If the values that you are trying to edit are plain key value pairs, you can create a class which holds these values as properties and serialize this class object into an XML file. You can deserialize the class and assign the values to the DataGridView.

You could also create a custom configuration and store it separately from App.config / Web.config file. This will be similar to what NHibernate or spring.Net configuration files are stored with a reference to them in the configsections key.

Here is a link how to creat your own custom configuration. MSDN link

Nilesh Gule
Okay, that is one way to do it, but it apparently involves plenty of extra coding. On the other hand, in Settings page I can change a type of one application setting to System.Data.DataSet, and this made me think that it's possible to just bind that setting somehow to a DataGridView, and make everything work with very few lines of code. I just need those lines :-)
Dialecticus
A: 

Here's how I did it. Class MyMap holds value pairs. They must be properties, because DatGridView doesn't work with fields. MyMapCollection holds the collection of MyMaps, as BindingList (allows adding rows in DataGridView). This class is needed to make Visual Studio settings editor happy, couldn't make it work with plain BindingList. So:

public class MyMap {
    public String FirstField { get; set; }
    public String SecondField { get; set; }
}

public class MyMapCollection : BindingList<MyMap>
{
    public MyMapCollection Clone()
    {
        MyMapCollection result = new MyMapCollection();

        foreach (MyMap map in this)
            result.Add(new MyMap() {
                FirstField = map.FirstField, SecondField = map.SecondField });

        return result;
    }
}

Function Clone creates a deep copy of the object, so that data is not changed directly on the object in Settings.Default, but when the users says so. In settings editor you would add an item of type MyMapCollection, called say TheValues, and use very simple it in the code:

myDataGridView.DataSource = Settings.Default.TheValues.Clone();

If data should be changed back to settings (when users clicks OK) then change settings accordingly:

Settings.Default.TheValues = (MyMapCollection)myDataGridView.DataSource;

Using a DataTable or DataSet instead of MyMapCollection is also possible, but this solution allows me to use TheValues in the rest of the code, which is even sweeter than DataSet could have been.

Dialecticus