日期:2014-05-18  浏览次数:21143 次

给动态生成的控件添加事件的代码如何写
private void head_Load(object sender, EventArgs e)
  {
  PictureBox[] t = new PictureBox[12];
   
  for(int i=0;i <10;i++) 
  { 
  t[i]=new PictureBox();
  t[i].SizeMode =System.Windows.Forms.PictureBoxSizeMode.AutoSize;
  t[i].Left = t[i].Width * i ;
  t[i].Image = Image.FromFile(@"d:\head4.gif");
  t[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
  this.Controls.Add(t[i]); 
  t[i].MouseMove += new MouseEventHandler(head_MouseMove);
  }

  }

  void head_MouseMove(object sender, MouseEventArgs e)
  {
   
  }  
我想在这10个动态生成的控件上添加鼠标移动事件,当移动到第1个图片上的时候显示弹出hello_1,移动到第2个时弹出hello_2,依此类推。代码应该如何写

------解决方案--------------------
不是已经写出来了吗?

PictureBox[] t = new PictureBox[12];

for(int i=0;i <10;i++)
{
t[i]=new PictureBox();
t[i].Tag="hello_"+i.Tostring();
t[i].SizeMode =System.Windows.Forms.PictureBoxSizeMode.AutoSize;
t[i].Left = t[i].Width * i ;
t[i].Image = Image.FromFile(@"d:\head4.gif");
t[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Controls.Add(t[i]);
t[i].MouseMove += new MouseEventHandler(head_MouseMove);


void head_MouseMove(object sender, MouseEventArgs e)
{
PictureBox temp=(PictureBox)sender;
if(temp.Tag.Tostring()=="")
MessageBox.show(temp.Tag.Tostring());
}
------解决方案--------------------
t[i].MouseMove += new MouseEventHandler(head_MouseMove);
------解决方案--------------------

我觉得要实现楼主的功能,必须先在代码中先写好各个控件的事件代码,动态创建后才能转到相应的事件执行。

按楼主的代码看来,可以创建一个全局的PictureBox数组来保存所有动态创建控件,然后再创建一个全局的字符数组来保存各个PictureBox的MouseMove事件,创建事件的时候写成
t[i].MouseMove += new MouseEventHandler(head_MouseMove[i]) //假设head_MouseMove已经定义成一个字符串数组了

然后再写各个head_MouseMove里面的所记录的事件。

由于电脑不方便,代码我没有测试,希望楼主测试后告诉我一声,如果有错,请楼主忽略我的回复,谢谢。
------解决方案--------------------
不好意思,我刚刚写错了一点,是定义一个事件组才行。
------解决方案--------------------
xuexi
------解决方案--------------------
C# code

private void head_Load(object sender, EventArgs e)
        {
            PictureBox[] t = new PictureBox[12];
         
            for(int i=0;i <10;i++)
              {
                t[i]=new PictureBox();
                t[i].SizeMode =System.Windows.Forms.PictureBoxSizeMode.AutoSize;
                t[i].Left = t[i].Width * i ;
                t[i].Image = Image.FromFile(@"d:\head4.gif");
                t[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                t[i].Name = "pictureBox" + i.ToString();
                t[i].MouseMove += new MouseEventHandler(head_MouseMove);
                this.Controls.Add(t[i]);
              }

        }

        void  head_MouseMove(object sender, MouseEventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            string name = pb.Name.Replace("pictureBox","");
            MessageBox.Show("hello_" + name);
        }