使用以前的ComboBox值加载WinForm

时间:2019-01-21 12:14:01

标签: c#

我有三个ComboBox,可从文件夹和子文件夹获得价值。当我关闭WinForm时 并再次运行它,我必须再次设置ComboBoxs值。 我需要做的是保存先前选择的组合框

    private void Form1_Load(object sender, EventArgs e)
    {
        if (Directory.Exists(rootDirectory))
        {
            comboBox1.DataSource = Directory.GetDirectories(rootDirectory).Select(Path.GetFileName).ToList();
            comboBox1.SelectedIndexChanged += comboBox1_SelectedValueChanged;
            comboBox2.SelectedIndexChanged += comboBox2_SelectedIndexChanged;
            comboBox3.SelectedIndexChanged += comboBox3_SelectedIndexChanged;
            comboBox1.Enter += comboBox1_Enter;                
        }
        else
        {
            MessageBox.Show("Cannot find folder!!! ");
        }
    }

    private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
    {

        var parentDir = Path.Combine(rootDirectory, comboBox1.SelectedItem.ToString());
        comboBox2.DataSource = Directory.GetDirectories(parentDir).Select(Path.GetFileName).ToList();
    }

    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {            
        var parentDir = Path.Combine(rootDirectory, comboBox1.SelectedItem.ToString(), comboBox2.SelectedItem.ToString());
        comboBox3.DataSource = Directory.GetDirectories(parentDir).Select(Path.GetFileName).ToList();
   }

    private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
    {
        var parentDir = Path.Combine(rootDirectory, comboBox1.SelectedItem.ToString(), comboBox2.SelectedItem.ToString(), comboBox3.SelectedItem.ToString());
     }

2 个答案:

答案 0 :(得分:2)

1-选择组合框

2-转到“属性”>“数据”>(“应用程序设置”)

3-将应用程序设置添加到“文本”属性

4-在FormClosed事件上保存应用程序设置

保存设置:

private void Form_FormClosed(object sender, FormClosedEventArgs e)
{
    Settings.Default.Save();
}

积分here

答案 1 :(得分:0)

首先,该小说对列出目录,子目录和文件不正确。使用下拉菜单的好主意。

在获胜表格中使用“ TreeView”组件。

示例:https://www.c-sharpcorner.com/article/display-sub-directories-and-files-in-treeview/

因此,您只能在树视图中保存/设置选定的值。

注意:您还可以查看递归函数。