C#自动生成EventHandler
我有一个程序,可以逐行读取文件,并将字符串放入tableLayoutPanel,但是如何为tableLayoutPanel中的每个标签创建eventHandler 以下是我正在使用的代码:C#自动生成EventHandler,c#,event-handling,C#,Event Handling,我有一个程序,可以逐行读取文件,并将字符串放入tableLayoutPanel,但是如何为tableLayoutPanel中的每个标签创建eventHandler 以下是我正在使用的代码: Label label = new Label(); label.Name = "MyNewLabel"; label.ForeColor = Color.Red; label.Text = line; tableLayoutPanel1.RowCount++; tableLayoutPanel1.RowSt
Label label = new Label();
label.Name = "MyNewLabel";
label.ForeColor = Color.Red;
label.Text = line;
tableLayoutPanel1.RowCount++;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Controls.Add(label, 0, tableLayoutPanel1.RowCount + 1);
每个标签都需要打开一个网页,url必须是它自己的文本
我已经试过了:
foreach (Control x in panel1.Controls)
{
label.Click += HandleClick;
}
与
它就是不起作用
新问题: 主要问题由Jay Walker解决,但现在我有另一个问题。并非所有标签都与eventHandler一起使用。以下是主要代码:
string line;
System.IO.StreamReader file = new System.IO.StreamReader("research.dat");
while ((line = file.ReadLine()) != null)
{
Label label = new Label();
label.Name = "MyNewLabel";
label.ForeColor = Color.Red;
label.Text = line;
label.Click += HandleClick;
tableLayoutPanel1.RowCount++;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Controls.Add(label, 0, tableLayoutPanel1.RowCount + 1);
}
结合:
private void HandleClick(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.White;
}
一些标签背景会变为白色,而相同的标签背景则不会变为白色。执行以下操作:
label.Click += Eventhandler;
创建标签后为什么不在创建标签时添加处理程序,而不是稍后通过控件上的循环(您可能应该引用
x
而不是标签
)
Label label = new Label();
label.Name = "MyNewLabel";
label.ForeColor = Color.Red;
label.Text = line;
// add the handler here
label.Click += HandleClick;
tableLayoutPanel1.RowCount++;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Controls.Add(label, 0, tableLayoutPanel1.RowCount + 1);
如果确实希望它在foreach循环中执行:
foreach (Control c in panel1.Controls) {
if (c.Type == typeof(Label)) { //or something like that...
c.Click += HandleClick;
}
}
您正在将标签添加到
tableLayoutPanel1
,但是,您正在循环panel1
控件(并将标签指定给label
,而不是x
,但是在下面的回答中对此进行了注释)……对吗?您能否详细说明“一些标签背景变为白色,而相同的背景不会变为白色?”.相同的是什么?
foreach (Control c in panel1.Controls) {
if (c.Type == typeof(Label)) { //or something like that...
c.Click += HandleClick;
}
}