簡體   English   中英

如何使用DirectoryInfo填充列表框

[英]How to use DirectoryInfo to populate a 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;
    }

這看起來似乎應該可以工作。 但這並沒有用我想要的內容填充列表。 有任何想法嗎?

剛在我的機器上嘗試了您的代碼段,它就可以正常工作(我修改了路徑)。

        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”來表示字符串文字。

嘗試這個 :

//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;
}

您應該將路徑變量設為該類的成員。 這樣,您可以確保兩種方法使用相同的路徑。 但這不是造成您問題的原因。 組成圖像位置時,它是缺少的斜線(如@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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM