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

如何写动态创建的窗体中控件的click事件?
目前有From1以及Form1上的button1,
我想根据button1的click事件,创建一个新的窗体form2,

form2中同时创建button2,
如何写button2的click事件呀?在button2的click事件中,窗体form2关闭,如何写代码,求高手指点

------解决方案--------------------
C# code
Form f = new Form();
                Button btn = new Button();
                btn.Click += (o, j) => { f.Close(); };//点击关闭
                f.Controls.Add(btn);
                f.Show();

------解决方案--------------------
是创建一个新的窗体咋。
在Form1的button1_Click事件中定义调出窗体就行了。具体如下:
private void button1_Click(object sender, EventArgs e)
{
try
{
Form form2 = new Form();
InitForm(form2);

form2.ShowDialog();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}

private void InitForm(Form form2)
{
Button button2 = new System.Windows.Forms.Button();
button2.Location = new System.Drawing.Point(99, 111);
button2.Name = "button2";
button2.Size = new System.Drawing.Size(91, 33);
button2.TabIndex = 0;
button2.Text = "button2";
button2.UseVisualStyleBackColor = true;

form2.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
form2.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
form2.CancelButton = button2;
form2.ClientSize = new System.Drawing.Size(292, 273);
form2.Controls.Add(button2);
form2.Name = "Form2";
form2.Text = "Form2";
form2.ResumeLayout(false);
}

窗体的CancelButton 这个属性就是点击canelButton,可以关闭该窗体
------解决方案--------------------
Form1
button1.Click +=(o,e) => {Form2 f = new Form2();f.Show();}
Form2
button1.Click +=(o,e) => {this.Close();}