Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void Form2_Load(object sender, EventArgs e)
       {
           string path = @"\\192.168.**.**\**\**";
           string[] dirs = Directory.GetDirectories(path);

           // For folders in the directory
           foreach (string dir in dirs)
               listBox1.Items.Add(dir);
       }


private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            listBox2.Items.Clear();
            DirectoryInfo dir = (DirectoryInfo)listBox1.SelectedItem;
            foreach (FileInfo img in dir.GetFiles())
                listBox2.Items.Add(img);            
        }

//  Error Occur >>>> An unhandled exception of type 'System.InvalidCastException'
Posted

Well, what did you expect?
Look at your code:
C#
foreach (string dir in dirs)
   listBox1.Items.Add(dir);

C#
DirectoryInfo dir = (DirectoryInfo)listBox1.SelectedItem;
So every item in the ListBox os a string, and you are trying to cast it to a DirectoryInfo. There is no such cast!

Try:
C#
DirectoryInfo dir = new DirectoryInfo(listBox1.SelectedItem);
 
Share this answer
 
Comments
Kornfeld Eliyahu Peter 27-Oct-15 4:42am    
Are you feeling pro, bro? :-)
Nigol_Learner 27-Oct-15 5:18am    
listBox2.Items.Clear();
// DirectoryInfo dir = (DirectoryInfo)listBox1.SelectedItem;
>>>>>>>>>>>>>>DirectoryInfo dir = new DirectoryInfo(listBox1.SelectedItem);
foreach (FileInfo img in dir.GetFiles())
listBox2.Items.Add(img);

>>>>>>>(listBox1.SelectedItem)getting red underline

the Error is :
(Severity Code Description Project File Line
Error CS1503 Argument 1: cannot convert from 'object' to 'string' picView C:\Users\User\Documents\Visual Studio 2015\picView\picView\Form2.cs)
OriginalGriff 27-Oct-15 6:11am    
Oh come on!
If you are writing code like this you should be able to sort that out!

DirectoryInfo dir = new DirectoryInfo((string) listBox1.SelectedItem);
Nigol_Learner 27-Oct-15 22:06pm    
thank you bro,,,,now its work.
C#
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    listBox2.Items.Clear();
    DirectoryInfo dir = new DirectoryInfo(listBox1.Text);
    foreach (FileInfo img in dir.GetFiles())
    {
        // Adds the full path
        //listBox2.Items.Add(img.FullName);

        // Adds just the filename
        listBox2.Items.Add(img.Name);
    }
}
 
Share this answer
 
Comments
Nigol_Learner 27-Oct-15 22:07pm    
its work too bro thanks.
DirectoryInfo dir = new DirectoryInfo(listBox1.SelectedItem);

To

DirectoryInfo dir = new DirectoryInfo(listBox1.Text);

//This works.
 
Share this answer
 
Comments
Nigol_Learner 27-Oct-15 22:08pm    
right bro.... thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900