如何在foreach循环中指定pictureBox的名称

时间:2017-02-07 09:52:52

标签: c# winforms foreach

我尝试过使用TagNameTextIndexOf。每一次,我都得到第一个名字,那就是它。这是代码:

// Perform scanning
for (;;)
{
    List<System.Drawing.Image> images = this.ScannerDevice.PerformScan().ToList();

    // Show picture in window
    this.Invoke((MethodInvoker)delegate
    {
         this.FrontImage = images[0];

         foreach (System.Drawing.Image image in images)
         {
               PictureBox pf = new PictureBox();
               pf.SizeMode = PictureBoxSizeMode.StretchImage; pf.Height = 150; pf.Width = 170;                                                          
               pf.Image = image;                        
               pf.Click += new EventHandler(pictureClicked);
               flowLayoutPanel1.Controls.Add(pf);
               pf.Tag=flowLayoutPanel1.Controls.Count;
         }                            
         ScanFinishedEventArgs eventArgs = new ScanFinishedEventArgs { AcceptScan = true };
         this.ScanFinished?.Invoke(this, eventArgs);
         label1.Text = Convert.ToString(flowLayoutPanel1.Controls.Count);
    });                       
}

void pictureClicked(object sender, EventArgs e)
{
      if (selectedPicture != null)
          selectedPicture.BorderStyle = BorderStyle.None;
      selectedPicture = (PictureBox)sender;
      selectedPicture.BorderStyle = BorderStyle.FixedSingle;            
      pictureBox1.Image = selectedPicture.Image;
      label2.Text = Convert.ToString(pf.Tag);
}

此外,当我点击某个图片框时,我想稍后使用该名称显示在另一个标签中。 此外,我尝试使用anonymous types但无法将其与图像对象一起使用。我做错了什么?

1 个答案:

答案 0 :(得分:1)

我刚做完这件事似乎有效。添加3个图像,每个图像根据当时的索引值命名。设置标签显示图像计数。单击图片处理程序会在单击图像时在消息框中显示该名称。

private void button1_Click(object sender, EventArgs e)
{
    int index = 0;

    foreach (Image image in images.Images)
    {
        PictureBox pf = new PictureBox();
        pf.SizeMode = PictureBoxSizeMode.StretchImage;
        pf.Height = 50;
        pf.Width = 50;
        pf.Click += new EventHandler(PictureClicked);
        pf.Name = index.ToString();
        pf.Image = image;
        flowLayoutPanel1.Controls.Add(pf);

        index++;
    }

    lblImagecount.Text = index.ToString();
}

private void PictureClicked(object sender, EventArgs e)
{
    MessageBox.Show(((PictureBox) sender).Name);
}