这里,我在运行时借助以下运行良好且良好的代码创建了几个控件。但是与此同时,我还必须对运行时生成的这些控件的事件执行某些任务
private void btnExtra_Click(object sender, EventArgs e)
{
AddNewLabel();
}
int count = 1;
public System.Windows.Forms.Label AddNewLabel()
{
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
lbl.Name = "LabelX" + this.count.ToString();
lbl.ForeColor = Color.Black;
lbl.Font = new Font("Sego UI", 8, FontStyle.Bold);
lbl.Top = count * 25;
lbl.Left = 100;
lbl.Text = "Label 1 " + this.count.ToString();
lbl.BringToFront();
panel4.Controls.Add(lbl);
count = count + 1;
return lbl;
}
答案 0 :(得分:1)
你可以试试吗
public System.Windows.Forms.Label AddNewLabel()
{
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
lbl.Name = "LabelX" + this.count.ToString();
lbl.ForeColor = Color.Black;
lbl.Font = new Font("Sego UI", 8, FontStyle.Bold);
lbl.Top = count * 25;
lbl.Left = 100;
lbl.Text = "Label 1 " + this.count.ToString();
lbl.DoubleClick += Lbl_DoubleClick;
lbl.BringToFront();
panel4.Controls.Add(lbl);
count = count + 1;
return lbl;
}
private void Lbl_DoubleClick(object sender, EventArgs e)
{
((Label)sender).Text = "Double Click";
}
答案 1 :(得分:1)
手动创建事件,连接处理程序。
private void lblMyLabel_Click(object sender, EventArgs e)
{
//Add Code here.
}
public System.Windows.Forms.Label AddNewLabel()
{
int count = 1;
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
lbl.Name = "LabelX" + count;
lbl.ForeColor = Color.Black;
lbl.Font = new Font("Sego UI", 8, FontStyle.Bold);
lbl.Top = count * 25;
lbl.Left = 100;
lbl.Text = "Label 1 " + count;
lbl.BringToFront();
//Wire relevant event handler here
lbl.Click += lblMyLabel_Click;
panel4.Controls.Add(lbl);
count ++;
return lbl;
}
答案 2 :(得分:0)
在运行时生成多个事件
public System.Windows.Forms.Label AddNewLabel()
{
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
lbl.Name = "LabelX" + this.count.ToString();
lbl.Top = 85;
lbl.Left = 100;
lbl.Text = "Label"+count;
lbl.AutoSize = true;
panel4.Controls.Add(lbl);
//multiple events
lbl.MouseMove += Control_NewEvent1;
lbl.MouseDown += Control_NewEvent2;
count = count + +;
lbl.BringToFront();
return lbl;
}
//Events
private void Control_NewEvent1(object sender, EventArgs e)
{
((Label)sender).ForeColor = Color.White;
}
private void Control_NewEvent2(object sender, EventArgs e)
{
((Label)sender).BackColor = Color.Black;
}