我有一个可编辑的ComboBox。用户输入文本并按保存按钮。他们的文字变成了字符串。
我需要它在运行时创建一个新的用户设置为app.config的名称,他们的字符串。(我认为这部分现在起作用了)。
然后将另一个ComboBox的选定项保存到该设置中。(对象引用未设置错误)。
这是为了创建一个自定义预置,它将保存程序中的每个控件状态、复选框、文本框等。
// Control State to be Saved to Setting
Object comboBox2Item = ComboBox2.SelectedItem;
// User Custom Text
string customText = ComboBox1.Text;
// Create New User Setting
var propertyCustom = new SettingsProperty(customText);
propertyCustom.Name = customText;
propertyCustom.PropertyType = typeof(string);
Settings.Default.Properties.Add(propertyCustom);
// Add a Control State (string) to the Setting
Settings.Default[customText] = (string)comboBox2Item;
在这部分我得到了一个错误。
Settings.Default[customText] = (string)comboBox2Item;
异常:引发:“对象引用未设置为对象实例”。
我尝试将ComboBox1.Text设置为一个对象,而不是字符串,但也有相同的错误。文本和字符串也不是空的。
Object customText = ComboBox1.Text;
,这是我想要做的事情的视觉,
发布于 2016-09-13 11:13:29
原来的答案:
我还没有尝试向文件中添加一个新的设置,但是我不得不更新它。下面是一些用于保存和检索保存到文件中的更改的代码。我知道它并没有直接回答这个问题,但是应该为您指明正确的方向,说明应该查看和使用哪些类。
一旦我有了喘息的时间,我将尝试更新以直接回答这个问题。
public static void UpdateConfig(string setting, string value, bool isUserSetting = false)
{
var assemblyPath = AppDomain.CurrentDomain.BaseDirectory;
var assemblyName = "AssemblyName";
//need to modify the configuration file, launch the server with those settings.
var config =
ConfigurationManager.OpenExeConfiguration(string.Format("{0}\\{1}.exe", assemblyPath, "AssemblyName"));
//config.AppSettings.Settings["Setting"].Value = "false";
var getSection = config.GetSection("applicationSettings");
Console.WriteLine(getSection);
var settingsGroup = isUserSetting
? config.SectionGroups["userSettings"]
: config.SectionGroups["applicationSettings"];
var settings =
settingsGroup.Sections[string.Format("{0}.Properties.Settings", assemblyName)] as ClientSettingsSection;
var settingsElement = settings.Settings.Get(setting);
settings.Settings.Remove(settingsElement);
settingsElement.Value.ValueXml.InnerText = value;
settings.Settings.Add(settingsElement);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
编辑答复:
我做了一个快速的谷歌搜索,并在MSDN论坛上找到了一个被接受的答案。MSDN问题。为了使add生效,您必须调用属性类的保存。考虑到数据库事务,在调用commit之前,它不会生效。
因此,代码中似乎缺少的是:Properties.Settings.Default.Save();
,它应该是您的Settings.Default.Properties.Add(propertyCustom);
之后的下一行。
https://stackoverflow.com/questions/39476483
复制