日期:2014-05-17  浏览次数:21216 次

pictureBox如何循环赋值
OpenFileDialog ofd = new OpenFileDialog();
  ofd.Multiselect = true;
  string[] picArr;
  if (ofd.ShowDialog() == DialogResult.OK)
  {
  picArr = ofd.FileNames;
  for (int i = 0; i<picArr.Length;i++ )
  {
  persondata.Add(new person(i.ToString()));
  bmp = (Bitmap)Image.FromStream(GetImgStream(picArr[i]));
  image = new Emgu.CV.Image<Bgr, Byte>(bmp);
  sbmp = new Bitmap(128, 128, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
  norm = new Emgu.CV.Image<Gray, Byte>(sbmp);
  int x = HJFace.FaceLocated(image.Ptr, norm.Ptr, persondata[j].Pfeature[0], 0);
  if (x == 0)
  {
  sbmp = IplImagePointerToBitmap(norm.Ptr);
  pictureBox1.Image = sbmp;
  if (sbmp == null)
  {
  continue;
  }

  //PictureBox pb = (PictureBox)this.Controls["pictureBox" + i.ToString()]; 
  //(Controls["pictureBox" + i.ToString()] as PictureBox).Image = sbmp;
  //pb.Image = sbmp;

  //((PictureBox)picFaecArr.GetValue(i)).Image = sbmp;
  //string str = string.Format("picture{0}", i);
  //((PictureBox)str).Image = sbmp;
  }
这样赋值老是出错

------解决方案--------------------
好像用了第三方库?
什么异常?
哪里出错?


好的回答的前提是有一个好的问题。
------解决方案--------------------
C# code
 object o = this.GetType().GetField("pictureBox" + i, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(this);
 PictureBox pb= (PictureBox )o;
pb.Image = sbmp;

------解决方案--------------------
探讨

直接用pictureBox1.Image = sbmp不会出错,我想循环赋值

------解决方案--------------------
PictureBox pb = (PictureBox)this.Controls["pictureBox" + i.ToString()];

你判断一下控件是否存在
------解决方案--------------------
很明显,你需要判断一下,有些拼出来的是不存在的
C# code
Control cl=Controls["pictureBox" + i];
                    if (cl is PictureBox)
                    {
                        (cl as PictureBox).Image = null;
                    }

------解决方案--------------------
看看,大家找到问题了吧。
------解决方案--------------------
Controls["pictureBox" + i.ToString()]为null了,
或者Controls["pictureBox" + i.ToString()] as PictureBox 为null.
设置个断点,看看变量值,很容易解决的。
------解决方案--------------------
探讨

还是不行引用:
C# code

object o = this.GetType().GetField("pictureBox" + i, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(this);
PictureBox pb= (……

------解决方案--------------------