Gregor Menih
Gregor Menih

Reputation: 5116

Dynamically generating events in c#?

I generate a bunch of linkLabels in c#. What I want is to fill textBox1 with an URL, which is different with each linkLabel. How would I generate dynamic events? This is an example:

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++;
}

The node text should be tempAtt.Value, and on click the textBox1 should be filled with att.Value

Upvotes: 0

Views: 223

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273169

You cannot pass dat to the event directly, you'll have to get at it from inside the handler some other way.

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;
    ....
}

Upvotes: 2

Related Questions