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 comboBox 1 as "Unbable 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.

What you neded to do is use the new operator:

DirectoryInfo dir = new DirectoryInfo(comboBox2.SelectedItem.ToString());

Just remember that the DirectoryInfo constructor requires the full path of the directory. The Path.Combine() method works well in combining the different parts of a path into one string.

On a side note, the 2 foreach loops are repetitive and can be combined into 1 for loop:

        DirectoryInfo di = new DirectoryInfo(@"\\Path\CAMR");
        var tempDirectoryCollection = di.GetDirectories();
        int pathCount = tempDirectoryCollection.Count()
        var paths = new String[pathCount];
        int i = 0;
        for (;i < pathCount;i++ )
        {
            var fi = tempDirectoryCollection[i];
            comboBox2.Items.Add(fi.Name);
            paths[i] = fi.FullName;
        }

Edited 1 Year Ago by tinstaafl

This question has already been answered. Start a new discussion instead.