3

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

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

上一个按钮没有线索。

4

2 回答 2

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));
   }
于 2012-11-14T04:12:59.667 回答
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
}
于 2012-11-14T04:50:49.793 回答