C#永久添加并保存项目到组合框

时间:2017-08-12 20:00:23

标签: c# winforms

大家!

我在combobox的属性中收集了一些项目。我想通过在组合框中编写文本然后使用按钮事件在我的组合框中添加新项目:

private void button2_Click_1(object sender, EventArgs e)
    {
        cbx_unix_dir.Items.Add(cbx_unix_dir.Text);
    }

但是在下次启动我的程序时 - 我添加的项目在组合框中不存在。我错了什么?我需要将所有添加的项目保存在我的组合框中。方法InitializeComponents()可能有问题吗?可能是我要在之前添加活动吗? 非常感谢你。

1 个答案:

答案 0 :(得分:2)

ComboBox没有保存和重新加载项目的功能。

您可以在关闭窗口将项目存储到.NET Settings file并在加载表单上重新加载:

    private void Form1_Load(object sender, EventArgs e)
    {
        if (Settings.Default.cboCollection != null)
            this.cbx_unix_dir.Items.AddRange(Settings.Default.cboCollection.ToArray());
    }


    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        ArrayList arraylist = new ArrayList(this.cbx_unix_dir.Items);
        Settings.Default.cboCollection = arraylist;
        Settings.Default.Save();
    }

    //A button to add items to the ComboBox
    private void button2_Click_1(object sender, EventArgs e)
    {
        cbx_unix_dir.Items.Add(cbx_unix_dir.Text);
    }
相关问题