如何使用DirectoryInfo填充列表框

时间:2013-10-30 18:09:30

标签: c# listbox

我目前正在尝试查看目录以查找.jpg文件并在列表框中显示结果。然后,当我这样做时,我想选择一个图像并将其显示在图片框中。

这是我的代码:

    private void Form1_load(object sender, EventArgs e)
    {
        string filepath = "F:\\Apps Development\\Coursework\\3_Coursework\\3_Coursework\\bin\\Debug\\Pics";
        DirectoryInfo dirinfo = new DirectoryInfo(filepath);
        FileInfo[] images = dirinfo.GetFiles("*.jpg");
        foreach (FileInfo image in images) 
        {  
            lstImages.Items.Add(image.Name);
        }
    }

    private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
    {
        string filepath = "F:\\Apps Development\\Coursework\\3_Coursework\\3_Coursework\\bin\\Debug\\Pics";
        pictureBox1.ImageLocation = filepath + lstImages.SelectedItem.ToString();
        pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    }

这看起来好像应该有效。但它没有填写我想要的列表。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

刚尝试了我的机器上的代码片段,它工作正常(我修改了路径)。

        string filepath = @"c:\temp";
   DirectoryInfo dirinfo = new DirectoryInfo(filepath);
   FileInfo[] images = dirinfo.GetFiles("*.*");
   var list = new List<string>();
   foreach (FileInfo image in images) 
   {  
        list.Add(image.Name);      

   }
   lstImages.DataSource = list;

所以我认为这与你如何将目录传递给构造函数有关。建议你使用@“blahblah”来表示像我上面那样的字符串文字。

答案 1 :(得分:0)

试试这个:

//load all image here
public Form1()
{
    InitializeComponent();
    //set your directory
    DirectoryInfo myDirectory = new DirectoryInfo(@"E:\MyImages");
    //set file type
    FileInfo[] allFiles = myDirectory.GetFiles("*.jpg");
    //loop through all files with that file type and add it to listBox
    foreach (FileInfo file in allFiles)
    {
            listBox1.Items.Add(file);
    }
}

//bind clicked image with picturebox
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Make selected item an image object
    Image clickedImage = Image.FromFile(@"E:\MyImages\" + listBox1.SelectedItem.ToString());
    pictureBox1.Image = clickedImage;
    pictureBox1.Height = clickedImage.Height;
    pictureBox1.Width = clickedImage.Width;
}

答案 2 :(得分:0)

您应该将路径变量设为该类的成员。这样,您可以确保两种方法都使用相同的路径。但这不是你问题的原因。在撰写图像位置时,这是缺失的斜线(正如@varocarbas在评论中已经说明的那样)。

要避免此类问题,您应该使用静态Path类。使用LINQ:

也可以更加优雅地填充列表
string filepath = @"F:\Apps Development\Coursework\3_Coursework\3_Coursework\bin\Debug\Pics";

private void Form1_load(object sender, EventArgs e)
{
    lstImages.Items.AddRange(Directory.GetFiles(filepath, "*.jpg")
                                      .Select(f => Path.GetFileName(f)).ToArray());
}

private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
{
    pictureBox1.ImageLocation = Path.Combine(filepath, lstImages.SelectedItem.ToString());
}