简体   繁体   English

应用程序设置未保存

[英]Application setting is not saved

I want to save a StringDictionary into the Application Settings in order to fill my listbox lbc_lastCustomersVisited with saved values at application launch. 我想将StringDictionary保存到“应用程序设置”中,以便在应用程序启动时用保存的值填充列表框lbc_lastCustomersVisited

Here is my application setting (XML format) : 这是我的应用程序设置(XML格式):

<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="Wibe_EFI.Properties" GeneratedClassName="Settings">
    <Profiles />
    <Settings>
        <Setting Name="ApplicationSkinName" Type="System.String" Scope="User">
            <Value Profile="(Default)" />
        </Setting>
        <Setting Name="LastTimeWibeDataObtained" Type="System.String" Scope="User">
            <Value Profile="(Default)" />
        </Setting>
        <Setting Name="LastVisitedCustomer" Type="System.Collections.Specialized.StringDictionary" Scope="User">
            <Value Profile="(Default)" />
        </Setting>
  </Settings>


In my form, I got a StringDictionary local variable : 在我的表单中,我得到了StringDictionary局部变量:

public partial class MainForm : XtraForm
{
    private StringDictionary lastVisitedCustomers = new StringDictionary();
    [...]
}


Here is how I fill my StringDictionary local variable : 这是我填写StringDictionary局部变量的方式:

private void btn_selectCustomer_Click(object sender, EventArgs e)
{
    DataRowView selectedRow = GetCustomersGridSelectedRow();
    lastVisitedCustomers.Add(GetCustomerID(selectedRow), String.Format("{0} - {1}", GetCustomerName(selectedRow), GetCustomerCity(selectedRow)));
}

( the StringDictionary is successfully filled ) StringDictionary已成功填充

At FormClosing , I save my setting : FormClosing ,我保存设置:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
        Settings.Default["ApplicationSkinName"] = UserLookAndFeel.Default.SkinName;
        Settings.Default.LastVisitedCustomer = lastVisitedCustomers;
        Settings.Default.Save();
}

The setting ApplicationSkinName is successfully saved but not the lastVisitedCustomer StringDictionary . 设置ApplicationSkinName已成功保存,但lastVisitedCustomer StringDictionary未成功保存。 Because when I load my settings at application launch time, Settings.Default.LastVisitedCustomer is null . 因为当我在应用程序启动时加载设置时, Settings.Default.LastVisitedCustomernull


Here is how I load my setting about the application skin (it works) : 这是我如何加载有关应用程序外观的设置的方法(有效):

public MainForm()
{
        InitializeComponent();
        InitSkinGallery();
        UserLookAndFeel.Default.SkinName = Settings.Default["ApplicationSkinName"].ToString();
}

But I cannot load my StringDictionnary right here because of a NullReferenceException . 但是由于NullReferenceException我无法在此处加载StringDictionnary
So I load it here : 所以我在这里加载:

private void MainForm_Load(object sender, EventArgs e)
{
    _mySqlCeEngine = new MySqlCeEngine(this);
    ShowHomePanel();
    LoadLastVisitedCustomers();
}

private void LoadLastVisitedCustomers()
{
    if (Settings.Default.LastVisitedCustomer.Count > 0)
    {
        lastVisitedCustomers = Settings.Default.LastVisitedCustomer;
    }
    lbc_lastCustomersVisited.DataSource = new BindingSource(lastVisitedCustomers, null);
    lbc_lastCustomersVisited.DisplayMember = "Value";
    lbc_lastCustomersVisited.ValueMember = "Key";
}

But at this moment, Settings.Default.LastVisitedCustomer is null and I don't understand why. 但是目前, Settings.Default.LastVisitedCustomer为null,我不明白为什么。 I tried some things like not using a local variable and read/write directly from Settings.Default.LastVisitedCustomer but I got the same problem. 我尝试了一些不使用局部变量的方法,而直接从Settings.Default.LastVisitedCustomer读取/写入,但遇到了同样的问题。

Thanks, 谢谢,

Hellcat. 地狱猫

EDIT : Added full Settings.settings file (XML view) 编辑 :添加了完整的Settings.settings文件(XML视图)

If you want to try, I tried to produce the error you get by creating a new formapplication: 如果您想尝试,我尝试通过创建一个新的formapplication来产生错误消息:

namespace WindowsFormsApplication2
{
  public partial class Form1 : Form
  {

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        test.Text = (string)Settings.Default["lastCustomers"];
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        Settings.Default["lastCustomers"] = test.Text;
        Settings.Default.Save();
    }
  }
}

In this example the code works. 在此示例中,代码有效。 Just create a new Form-Application and add a textbox into it with the name test . 只需创建一个新的Form-Application并在其中添加一个名为test的文本框即可。 Every time you close the program and restart it, the string you wrote into the textbox will be saved and reloaded into test.Text . 每次关闭程序并重新启动它时,写入文本框的字符串将被保存并重新加载到test.Text

Specifically in your case your constructor should then look like this: (Possible solution) 具体而言,您的构造函数应如下所示:(可能的解决方案)

public MainForm()
{
    InitializeComponent();
    InitSkinGallery();
    UserLookAndFeel.Default.SkinName = Settings.Default["ApplicationSkinName"].ToString();
    lastVisitedCustomers = (StringDictionary)Settings.Default["LastVisitedCustomer"];
}

Afterwards you save the settings the same way you loaded them: 之后,以与加载设置相同的方式保存设置:

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    Settings.Default["ApplicationSkinName"] = UserLookAndFeel.Default.SkinName;
    Settings.Default["LastVisitedCustomer"] = lastVisitedCustomers;
    Settings.Default.Save();
}

This should solve your problem! 这应该可以解决您的问题!

EDIT Oh and of course, your loading functions looks different then: 编辑哦,当然,您的加载函数看上去与以下不同:

private void MainForm_Load(object sender, EventArgs e)
{
    _mySqlCeEngine = new MySqlCeEngine(this);
    ShowHomePanel();
    LoadLastVisitedCustomers();
}


private void LoadLastVisitedCustomers()
{
    lbc_lastCustomersVisited.DataSource = new BindingSource(lastVisitedCustomers, null);
    lbc_lastCustomersVisited.DisplayMember = "Value";
    lbc_lastCustomersVisited.ValueMember = "Key";
}

I could not find any solution to store a Dictionary in the app settings so I decided to deal with a string and split it : 我找不到在应用程序设置中存储Dictionary任何解决方案,因此我决定处理一个string并将其拆分:

public partial class MainForm : XtraForm
{
    private Dictionary<string, string> lastVisitedCustomers;

    public MainForm()
    {
        InitializeComponent();
        InitSkinGallery();
        UserLookAndFeel.Default.SkinName = Settings.Default["ApplicationSkinName"].ToString();
        lastVisitedCustomers = StringToDictionary(Settings.Default["LastVisitedCustomer"].ToString());
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        Settings.Default["ApplicationSkinName"] = UserLookAndFeel.Default.SkinName;
        Settings.Default["LastVisitedCustomer"] = DictionaryToString(lastVisitedCustomers);
        Settings.Default.Save();
    }

    #region Dictionary management

    private string DictionaryToString(Dictionary<string, string> dic)
    {
        if (dic.Count == 0)
        {
            return string.Empty;
        }
        else
        {
            string dicString = string.Empty;
            int i = 0;
            foreach (KeyValuePair<string, string> entry in dic)
            {
                if (i == 0)
                {
                    dicString = String.Format("{0} ## {1}", entry.Key, entry.Value);
                    i++;
                }
                else
                {
                    dicString += String.Format(" -- {0} ## {1}", entry.Key, entry.Value);
                }
            }
            return dicString;
        }
    }

    private Dictionary<string, string> StringToDictionary(string str)
    {
        Dictionary<string, string> dic = new Dictionary<string,string>();
        if (String.IsNullOrEmpty(str))
        {
            return dic;
        }
        else
        {
            string[] entries = Regex.Split(str, " -- ");

            foreach (string entry in entries)
            {
                string[] kvp = Regex.Split(entry, " ## ");
                dic.Add(kvp[0], kvp[1]);
            }

            return dic;
        }
    }
}
    #endregion

For now, it works. 目前,它可以工作。
I hope it will helps anyone in my situation. 我希望它能对我所处的环境有所帮助。

Notice : You may have to modify my dictionary methods in order to handle every cases for Exceptions. 注意 :您可能必须修改我的字典方法,才能处理所有例外情况。 But I think this is okay now. 但我认为现在还可以。

Sorry for any english mistakes 对不起,任何英语错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM