发表于: other | 作者: | 日期: 2013/5/13 04:05

有时候需要在程序运行到一定时候或者某个事件之后需要动态生成控件,在C#下一般方式是:

private Button Db=new Button() ;
Db.Name=”Dy_Button” //设定名称
Db.Location=new Point(100,200);//设定位置
。。。。//其他属性设置
//这里添加消息处理
this.Controls.Add (Db);//添加到控件组中

这样就完成了动态生成,但是需要给控件添加消息处理事件
那么现在就需要在生成控件添加到控件组前增加如下语句:

DPB.MouseClick += new EventHandler(this.pictureBox_MouseClick);

现在编写这个消息处理的函数pictureBox_Click()

private void pictureBox_MouseClick(object sender,EventArgs e)
{
    MessageBox.Show(“click”);
}

这样完成了事件处理的添加
再看一个示例:
首先,创建一个全局变量”i “用来区分各个新的按钮:

private int i=0;

然后在已有的按钮中添加方法如下:

private void button1_Click(object sender, System.EventArgs e)
{
i++;
Button b = new Button();//创建一个新的按钮
b.Name=”b”+i;//这是我用来区别各个按钮的办法
System.Drawing.Point p = new Point(12,13+i*30);//创建一个坐标,用来给新的按钮定位
b.Location = p;//把按钮的位置与刚创建的坐标绑定在一起
panel1.Controls.Add(b);//向panel中添加此按钮
b.Click += new System.EventHandler(btn_click);//将按钮的方法绑定到按钮的单击事件中b.Click是按钮的单击事件
}

下面我们来讲如何对新建的按钮添加对应的事件方法btn_click():

private void btn_click(object sender, System.EventArgs e)
{
Button b1 = (Button)sender;//将触发此事件的对象转换为该Button对象
MessageBox.Show(“”+b1.Name);
}

至此就已经完成了动态创建按钮和事件
[整理自网络]

: https://blog.darkmi.com/2013/05/13/3232.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.