使用ComboBox选择作为另一个ComboBox的目录源,C#

时间:2016-04-18 10:33:41

标签: c# winforms combobox directory

所以我创建了一个表单,在.txt目录下创建一个directory文件和C:\Modules同名的表单。

我已经可以从.txt中选择ModuleSelectorComboBox个文件,现在我在上班时遇到的问题是使用在ModuleSelectorComboBox中选择的文件的名称来构成部分NoteSelectorComboBox中目录的名称。

    public Default()
    {
        InitializeComponent();

        System.IO.Directory.CreateDirectory(@"C:\Modules");
        string[] files = Directory.GetFiles(@"C:\Modules");
        foreach (string file in files)
            ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
    }

    private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
    {
        NewModule newmodule = new NewModule();

        newmodule.Show();

    }

    private void ModuleSelectorComboBox_SelectedValueChanged(object sender, EventArgs e)
    {
        richTextBox1.Clear(); //Clears previous Modules Text
        string ModulefileName = (string)ModuleSelectorComboBox.SelectedItem;
        string filePath = Path.Combine(@"C:\Modules\", ModulefileName + ".txt");

        if (File.Exists(filePath))
            richTextBox1.AppendText(File.ReadAllText(filePath));
        else
            MessageBox.Show("There's been a problem. Please restart the program. \nError 1", "Error 1", //error 1 is file deleted while the program is running
            MessageBoxButtons.OK,
            MessageBoxIcon.Exclamation,
            MessageBoxDefaultButton.Button1);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ModuleSelectorComboBox.Items.Clear();
        string[] files = Directory.GetFiles(@"C:\Modules");
        foreach (string file in files)
            ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
    }

    private void NoteSelectorComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        string ModulefileName = (string)ModuleSelectorComboBox.SelectedItem;
        string[] files = Directory.GetFiles(@"C:\Modules\" + ModulefileName); //THIS IS WHAT I HAVE TRIED BUT CANNOT GET TO WORK
        foreach (string file in files)
            NoteSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
    }
}

因此,如果&#39;模块1&#39;在ModuleSelectorComboBox中选择NoteSelectorComboBox的{​​{1}}目录列表将设置为C:\Modules\Module 1(即C:\Modules\<NAME OF SELECTED MODULE From ModuleSelectorComboBox>,因此该文件夹中的文件将显示在ComboBox中。< / p>

1 个答案:

答案 0 :(得分:0)

我创建了一个OnClick();已经解决了这个问题的事件。

private void button2_Click(object sender, EventArgs e)
    {
        string fileName = (string)ModuleSelectorComboBox.SelectedItem;
        NoteSelectorComboBox.Items.Clear();
        string[] files = Directory.GetFiles(@"C:\Modules\" + (string)ModuleSelectorComboBox.SelectedItem);
        foreach (string file in files)
            NoteSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
    }