使用DataGridView进行本地设置 [英] Use DataGridView for local settings

查看:96
本文介绍了使用DataGridView进行本地设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要简单的方式在我的应用程序中持久化和编辑一组字符串对。我相信具有两个顶点的DataGridView可以帮助我查看和编辑,我希望使用应用程序设置而不是数据库来存储数据(可能是DataSet作为设置类型)。我不能把所有的一切放在一起有没有办法?

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?

推荐答案

这是我做的。 MyMap类保存值对。它们必须是属性,因为DatGridView不适用于字段。 MyMapCollection将MyMaps的集合保存为BindingList(允许在DataGridView中添加行)。这个类是需要使Visual Studio设置编辑器快乐,无法使其与纯BindingList一起使用。所以:

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;
    }
}

功能克隆创建对象的深层副本,所以该数据没有直接在Settings.Default中的对象上更改,但是当用户这样说。在设置编辑器中,您将添加一个MyMapCollection类型的项,称为TheValues,并在代码中使用非常简单:

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();

如果数据应该更改回设置(用户单击确定时),请相应地更改设置: p>

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

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

使用DataTable或DataSet代替MyMapCollection也是可行的,但是这个解决方案可以让我使用TheValues其余的代码,比DataSet更加甜美。

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.

这篇关于使用DataGridView进行本地设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆