我有一个带有标签的Windows表单,我为所有标签创建了一个常见的点击事件处理程序。 该事件受代码约束。现在我需要在运行时创建更多标签,并将相同的事件处理程序绑定到那些动态创建的标签。我尝试了以下但是没有用。
private void Ctrl_Click(object sender, EventArgs e)
{
Control control = (Control)sender;
if (control is Label)
{
Label lbl = (Label)sender;
txtCaption.Text = lbl.Text;
cboFont.Text = lbl.Font.FontFamily.Name;
txtSize.Text = lbl.Font.Size.ToString();
chkBold.Checked = lbl.Font.Bold;
txtX.Text = lbl.Location.X.ToString();
txtY.Text = lbl.Location.Y.ToString();
txtWidth.Text = lbl.Width.ToString();
gbLogo.Visible = false;
gbControl.Visible = true;
gbDetail.Visible = false;
}
}
private void btnAddDynamic_Click(object sender, EventArgs e)
{
Label label = new Label();
int count = pl.Controls.OfType<Label>().ToList().Count;
label.Location = new Point(50, (25 * count) + 2);
label.AutoSize = true;
Graphics g = label.CreateGraphics();
label.Width =Convert.ToInt32(g.MeasureString(label.Text, label.Font).Width);
label.Name = "label_" + (count + 1);
label.Text = "label " + (count + 1);
label.TabIndex=0;
label.Click += new EventHandler(this.Ctrl_Click);
pl.Controls.Add(label);
}