我是一名使用 Visual C# 2010 的新手程序员。我正在尝试动态地(在运行时)创建一个新的 SettingsProperty 并将其添加到我的应用程序(新设置)中的 Settings.Default.Properties 集合中。这些属性本质上是用户定义的 View (存储在一个字符串中),我想保存它们以供以后重新加载。我试过使用下面的代码,但它似乎没有用。当我关闭应用程序时,新创建和保存的属性都消失了。
private void button6_Click(object sender, EventArgs e)
{
string connectionText = maskedTextBox3.Text;
string vusipsText = maskedTextBox2.Text;
string chartText = maskedTextBox1.Text;
string[] settingsArray = { connectionText, chartText, vusipsText };
string saveSettings = String.Join(":", settingsArray);
//configure new property
SettingsProperty property = new SettingsProperty("kri");
property.DefaultValue = saveSettings;
property.IsReadOnly = false;
property.PropertyType = typeof(string);
property.Provider = Settings.Default.Providers["LocalFileSettingsProvider"];
property.Attributes.Add(typeof(System.Configuration.UserScopedSettingAttribute), new System.Configuration.UserScopedSettingAttribute());
Settings.Default.Properties.Add(property);
//Properties.Settings.Default.Reload();
Settings.Default.Save();
ActiveForm.Close();
}
我怎样才能解决这个问题?
谢谢
最佳答案
您的代码看起来不错,但设置在您下次加载数据时不知道您的属性。如果您再次定义您的属性(在加载时),该值应该可用。这是我用来保存枚举的循环之外的工作示例:
If My.Settings.Properties(settingName) Is Nothing Then
Dim p = New Configuration.SettingsProperty(settingName)
p.Provider = My.Settings.Providers("LocalFileSettingsProvider")
p.Attributes.Add(GetType(Configuration.UserScopedSettingAttribute), _
New Configuration.UserScopedSettingAttribute())
p.PropertyType = GetType(SampleEnum)
My.Settings.Properties.Add(p)
If My.Settings(settingName) Is Nothing Then
My.Settings(settingName) = SampleEnum.DefaultValue
End If
End If
始终在启动时运行代码以创建属性,并在第一次创建值时也运行代码。
关于c# : Dynamically adding new User Settings to Settings. Default.Properties 集合,并在关闭表单后保存它们。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12611864/