Reputation: 113
I'm trying to show an image from a folder that the user selected.and if he slected a record that does not have any picture, it would show an image which is called
Empty.png
here's the code i wrote. how can i change it that it will fit what i wrote in the explaination?(the top of this question)
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;
}
}
Upvotes: 0
Views: 265
Reputation: 22001
I don't think you need to iterate through every file in the directory to acheive what you want
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;
Upvotes: 0
Reputation: 215
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;
}
}
}
Upvotes: 1
Reputation: 13150
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;
}
Upvotes: 2