一次一个地在十个图片框上显示许多图片

时间:2012-11-14 03:17:42

标签: c# .net winforms image picturebox

我的程序有十张图片,显示我想要的文件夹中的图像。添加下一个按钮和上一个按钮允许用户浏览下十张图片或最后十张图片。前十张图片成功显示,但下一张按钮仅在文件夹有二十张图片时才有效,如果图片十五张则会崩溃。 这是我的代码:

PictureBox[] myPicBoxArray = new PictureBox[10];
string path = @"\\Documents\Pictures\Camera";

private void Form1_Load(object sender, EventArgs e)
{
    myPicBoxArray[0] = pictureBox1;
    myPicBoxArray[1] = pictureBox2;
    myPicBoxArray[2] = pictureBox3;
    myPicBoxArray[3] = pictureBox4;
    myPicBoxArray[4] = pictureBox5;
    myPicBoxArray[5] = pictureBox6;
    myPicBoxArray[6] = pictureBox7;
    myPicBoxArray[7] = pictureBox8;
    myPicBoxArray[8] = pictureBox9;
    myPicBoxArray[9] = pictureBox10;
}

//Show button to display first ten pictures
private void showButton_Click(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles(path);
    int i = 0;
    foreach (string ofile in files)
    {
        myPicBoxArray[i].SizeMode = PictureBoxSizeMode.StretchImage;
        myPicBoxArray[i].Image = Image.FromFile(files[i]);

        i++;
        if (i >= 10)
            break;
    }
}

private void nextButton_Click(object sender, EventArgs e)//The problem is here,
{
    DirectoryInfo fileDir = new DirectoryInfo(path);
    while (i2 < 10)
    {
        myPicBoxArray[i2].SizeMode = PictureBoxSizeMode.StretchImage;
        if (i2 + 10 < picArrFileNames.Length)
        {
            myPicBoxArray[i2].Image = Image.FromFile(picArrFileNames[i2 + 10]);
        }
    }
}

对上一个按钮没有任何线索。

2 个答案:

答案 0 :(得分:1)

您可以简单地将这些图像存储在ImageList中,并使用属性myImageList.Images.Count来计算ImageList中的图像数量,而不是使用有限的数组。
问题解决了.. :)或者跟Lists一起使用myList.Count

您可以这样做:

   DirectoryInfo dir = new DirectoryInfo(filePath);
   foreach (FileInfo file in dir.GetFiles())
   {               
       this.myImageList.Images.Add(Image.FromFile(file.FullName));
   }

答案 1 :(得分:0)

我不知道你为什么要这样做:

if (i2 + 10 < picArrFileNames.Length)
  {
      myPicBoxArray[i2].Image = Image.FromFile(picArrFileNames[i2 + 10]);
  }

但是,请尝试使用此计数器,同时执行文件扩展名检查以避免系统文件,如以下MrGreen所建议的那样。

private void nextButton_Click(object sender, EventArgs e)//The problem is here,
    {
        DirectoryInfo fileDir = new DirectoryInfo(path);
        int count = fileDir.GetFiles().Length;            
        while (i2 < count)
        {
            myPicBoxArray[i2].SizeMode = PictureBoxSizeMode.StretchImage;
            if (i2 + 10 < picArrFileNames.Length)
            {
                myPicBoxArray[i2].Image = Image.FromFile(picArrFileNames[i2 + 10]);
            }                                               
        }            
    }

在这里的某个循环中使用它来进行扩展检查在此处的循环中使用它进行扩展检查

string e = Path.GetExtension("YourFilePathHere");
if (e == ".jpeg")
{
   //Do your stuff
}