在 c# 中动态生成事件

本文关键字:事件 动态 | 更新日期: 2023-09-27 18:35:09

我在c#中生成了一堆linkLabels。我想要的是用一个URL填充textBox1,每个链接标签都不同。如何生成动态事件?这是一个示例:

foreach (var node in nodes)
{
    HtmlAttribute att = node.Attributes["href"];
    HtmlAgilityPack.HtmlDocument tempDoc = new HtmlAgilityPack.HtmlDocument();
    tempDoc.LoadHtml(node.InnerHtml);
    var tempNode = tempDoc.DocumentNode.SelectSingleNode("//img[@alt]");
    HtmlAttribute tempAtt = tempNode.Attributes["alt"];
    LinkLabel ll = new LinkLabel();
    ll.Location = new Point(20, 20 * i);
    ll.Text = tempAtt.Value;
    this.Controls.Add(ll);
    i++;
}

节点文本应tempAtt.Value,单击时 textBox1 应填充att.Value

在 c# 中动态生成事件

你不能直接将 dat 传递给事件,你必须通过其他方式从处理程序内部获取它。

foreach (var node in nodes)
{
    ...
    LinkLabel ll = new LinkLabel();
    ...
    ll.Click += MyLabelClickHandler;
    this.Controls.Add(ll);
    i++;
}
void MyLabelClickHandler(object sender, Eventargs e)
{
    senderLabel = sender as LinkLabel;
    string text = senderlabel.text;
    ....
}