0

我正在尝试显示用户选择的文件夹中的图像。如果他选择了没有任何图片的记录,它将显示一个名为的图像

空.png

这是我写的代码。我怎样才能改变它以符合我在解释中写的内容?(这个问题的顶部)

            string[] fileEntries = Directory.GetFiles(@"C:\Projects_2012\Project_Noam\Files\ProteinPic");

            foreach (string fileName in fileEntries)
            {
                if (fileName.Contains(comboBox1.SelectedItem.ToString()))
                {
                    Image image = Image.FromFile(fileName);
                    // Set the PictureBox image property to this image.
                    // ... Then, adjust its height and width properties.
                    pictureBox1.Image = image;
                    pictureBox1.Height = image.Height;
                    pictureBox1.Width = image.Width;
                }
            }
4

3 回答 3

2
foreach (string fileName in fileEntries)
{
   if (fileName.Contains(comboBox1.SelectedItem.ToString()))
   {
     pictureBox1.Image = Image.FromFile(fileName);              
   }
   else
   {
     pictureBox1.Image = ImageFromFile("Empty.png");                
   }

   // Set the PictureBox image property to this image.
   // ... Then, adjust its height and width properties.
   pictureBox1.Image = image;
   pictureBox1.Height = image.Height;
   pictureBox1.Width = image.Width;

}
于 2012-06-08T10:09:37.047 回答
1
string[] fileEntries = Directory.GetFiles(@"C:\Projects_2012\Project_Noam\Files\ProteinPic");

        if (fileEntries.Length == 0)
        {
            Image image = Image.FromFile("Path of empty.png");
            pictureBox1.Image = image;
            pictureBox1.Height = image.Height;
            pictureBox1.Width = image.Width;
        }
        else
        {
            foreach (string fileName in fileEntries)
            {
                if (fileName.Contains(comboBox1.SelectedItem.ToString()))
                {
                    Image image = Image.FromFile(fileName);
                    pictureBox1.Image = image;
                    pictureBox1.Height = image.Height;
                    pictureBox1.Width = image.Width;
                }
            }
        }
于 2012-06-08T10:11:03.863 回答
0

我不认为你需要遍历目录中的每个文件来实现你想要的

        Image image;

        string imagePath = System.IO.Path.Combine(@"C:\Projects_2012\Project_Noam\Files\ProteinPic", comboBox1.SelectedItem.ToString());
        if (System.IO.File.Exists(imagePath))
        {
            image = Image.FromFile(imagePath);
        }
        else
        {
            image = Image.FromFile(@"C:\Projects_2012\Project_Noam\Files\ProteinPic\Empty.png");
        }

        pictureBox1.Image = image;
        pictureBox1.Height = image.Height;
        pictureBox1.Width = image.Width;
于 2012-06-08T10:21:10.503 回答