如何在表单中编辑和保存设置? [英] How to edit and save settings in a Form?

查看:95
本文介绍了如何在表单中编辑和保存设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个文本框,单选按钮,复选框等的表单。现在,我通过声明每个值并将其保存到程序设置中来分别保存它们的值:

I have a form that contains several text boxes, radio buttons, checkboxes etc. Right now I am saving their values respectively by declaring each one and saving to the programs settings:

Properties.Settings.Default.EmailFrom = txtbxEmailFrom.Text;

我想找到一种方法来遍历所有对象并尽可能保存它们的设置,所以我不必分别声明每个。

I would like to find a way to loop through all the objects and save their settings if possible so I don't have to declare each one individually.

有没有办法做到这一点?或一种更好的方式来保存我的文本框的文本,即复选框的选中状态&单选按钮等?

Is there a way to do this? Or a better way to save the text of my textboxes, the checkstate of checkboxes & radiobuttons etc?

推荐答案

您可以使用将属性绑定到应用程序设置

通过这种方式,您可以简单地通过调用 Properties.Settings.Default.Save(); 保存设置,您无需循环控件,因为属性绑定到设置,并且其值会自动推送进入更改设置。

This way you can simply save settings by calling Properties.Settings.Default.Save(); and you don't need to loop over controls, because the properties are bound to settings and their values automatically push into settings on change.

您可以使用设计器或代码将属性绑定到设置。

You can bind properties to settings using designer or using code.

使用Designer

在设计时选择控件,然后在属性网格的(ApplicationSettings)下为(PropertyBinding)单击 ... ,然后从对话框中将所需的属性绑定到设置。

select your control at design time, then in property grid, under (ApplicationSettings) click ... for (PropertyBinding) and from the dialog, bind the properties you need to the settings.

使用代码

您可以使用与代码相同的方式将属性绑定到设置做吧n使用代码进行数据绑定:

You can bind properties to settings, using code the same way you do it when data-binding using code:

this.textBox1.DataBindings.Add(
    new System.Windows.Forms.Binding("Text", Properties.Settings.Default, "Test", true,
        DataSourceUpdateMode.OnPropertyChanged));

保存设置

要保存设置,只需在设置对象中调用 Save(),例如 Closing 事件:

To save settings, it's enough to call Save() on settings object some where like Closing event of form:

Properties.Settings.Default.Save();

注意

除了可以使用其他设置控件之外,还可以使用 PropertyGrid 显示所有设置并进行编辑。

As an alternative to different controls for settings, you can also use a PropertyGrid to show all the settings and edit them.

这篇关于如何在表单中编辑和保存设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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