2012-06-08 48 views
0

我试图显示从文件夹中的图像,用户selected.and如果他slected不具有任何图片的记录,它会显示其被称为图像C#检查是否有图片应用

Empty.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; 
       } 
      } 
+0

这是什么意思“记录没有任何图片”?你想知道fileName是图像吗? –

+0

用户在comboBox.it中选择一条记录,不是针对他选择图片的具体记录,显示“空”图片 – Noam650

回答

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

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