Directory Info error while trying to upload directory folders to combobox2

时间:2015-12-10 01:33:41

标签: c#

I am trying to upload folders to comboBox 1 from the directory, and then at selection from comboBox 1 to comboBox2.

I have below code, I am getting error when I make selection from comboBox1 as

Unable to cast object of the type system.string to system.Io.DirectoryInfo

 private void Form_Load(object sender, EventArgs e)
 {
            DirectoryInfo di = new DirectoryInfo(@"\\Path\CAMR");
            paths = new String[di.GetDirectories().Count()];
            int i = 0;
            foreach (DirectoryInfo fi in di.GetDirectories())
            {
                comboBox1.Items.Add(fi.Name);
            }
            foreach (DirectoryInfo fi in di.GetDirectories())
            {
                paths[i] = fi.FullName;  
            }   
}

// I am getting error in the part below, as I am missing key part for conversion.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
         comboBox3.Items.Clear();
         //string dinf01 = comboBox2.SelectedItem.ToString();
         DirectoryInfo dir = (DirectoryInfo)comboBox2.SelectedItem;
         foreach (FileInfo fi in dir.GetFiles())
         {
             comboBox3.Items.Add(fi);
         }
  }

I need help with this part, all help and advise is appreciated.

Thanks.

1 个答案:

答案 0 :(得分:0)

You can do something like this:

 foreach (DirectoryInfo fi in di.GetDirectories())
     {
       ComboBoxItem item = new ComboBoxItem();
       item.Text = fi.Name;
       item.Value = fi.FullName; 
       comboBox1.Items.Add(item);
    }

Where ComboBoxItem is defined as :

public class ComboBoxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

So that you can retrieve the selected value using

comboBox1.SelectedItem as ComboboxItem).Value.ToString();

Hence your second loop will be like the following:

     DirectoryInfo dir = new DirectoryInfo(comboBox1.SelectedItem as ComboboxItem).Value.ToString());
     foreach (FileInfo fi in dir.GetFiles())
     {
         comboBox3.Items.Add(fi);
     }