How to edit and save settings in a Form?

我是研究僧i 提交于 2019-12-17 17:00:15

问题


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?


回答1:


You can use property binding to application settings.

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.

Using Designer

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.

Using Code

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 Settings

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

Properties.Settings.Default.Save();

Note

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




回答2:


One way of doing this would be to loop through all the controls and in each iteration check the type of the current control and save accordingly. However I'm not too sure what you can do about the RadioButtons/CheckBoxes.

foreach (var c in this.Controls)
{
    var _type = c.GetType();
    if (_type == typeof(TextBox))
    {
        // Cast it to a textbox and save it's text property
    }
    elseif (_type == typeof(ListBox)
    {
        // Cast it to a listbox and save it's items property
    }
    // So on...
 }


来源:https://stackoverflow.com/questions/34483338/how-to-edit-and-save-settings-in-a-form

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