我有数据将写入文本文件,然后通过按钮传输到组合框。但是下次我启动 gui 时,我在组合框中找不到以前写入的数据。无论如何要将数据保存在组合框中?
3 回答
            0        
        
		
不,如果您重新启动应用程序,则无法自动保留组合框的内容。您必须每次重新加载数据。
于 2013-11-13T14:59:04.900   回答
    
    
            0        
        
		
当然,有很多方法。我建议<appSettings>在app.config文件中使用。您可以轻松阅读这些设置。首先,添加对System.Configuration. 接下来,构建一些扩展方法以使该过程更容易:
public static class Extensions
{
    public static void SetValue(this KeyValueConfigurationCollection o,
        string key,
        string val)
    {
        if (!o.AllKeys.Contains(key)) { o.Add(key, val); }
        else { o[key].Value = val; }
    }
    public static string GetValue(this NameValueCollection o,
        string key,
        object defaultVal = null)
    {
        if (!o.AllKeys.Contains(key)) { return Convert.ToString(defaultVal); }
        return o[key];
    }
}
接下来,当您想从设置中获取值时,请执行以下操作:
var val = ConfigurationManager.AppSettings.GetValue("ComboBoxValue");
然后,当您要设置该值时,请执行以下操作:
var config = ConfigurationManager.OpenExeConfiguration(
    ConfigurationUserLevel.None);
var app = config.AppSettings.Settings;
app.SetValue("ComboBoxValue", comboBox.Text);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
于 2013-11-13T15:00:53.530   回答
    
    
            0        
        
		
首先为用户创建一个名为 Combovalues 类型的 stringCollection 和 Scope 的设置(如果您需要向其添加一些值)然后使用此代码(这是一个骨架代码,您可以选择应用验证和其他保存和删除规则):
        private BindingSource bs;
        public Form1()
        {
            InitializeComponent();
            bs = new BindingSource();
            bs.DataSource = Properties.Settings.Default.Combovalues;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = bs;
        }
        //button1 is for adding values.
        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                bs.Add(textBox1.Text);
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this will persist to disk the changes made
            //in this application session.
            Properties.Settings.Default.Save();
        }
        //button2 is for deleting values
        private void button2_Click(object sender, EventArgs e)
        {
            //removes the currently selected item in the combobox.
            bs.RemoveCurrent();
        }
于 2013-11-13T17:29:01.110   回答