Use DataGridView for local settings

倾然丶 夕夏残阳落幕 提交于 2019-12-11 07:32:06

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3568302/use-datagridview-for-local-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!