Mihael Keehl
Mihael Keehl

Reputation: 355

C# Automatically Generate EventHandler

I have a program which reads a file line by line, and put the string in a tableLayoutPanel, but how can I create an eventHandler for each label in the tableLayoutPanel?

Here is the code I'm using:

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);

Every label needs to open a webpage, and the url has to be it's own text.

I've already tried this:

foreach (Control x in panel1.Controls)
{
label.Click += HandleClick;
}

with

private void HandleClick(object sender, EventArgs e)
{
messageBox.Show("Hello World!");
}

It just doesn't work.


New Problem:

The main problem is solved by Jay Walker, but now I have another problem. Not all the labels work with the eventHandler. Here is the main code:

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

in combination with:

    private void HandleClick(object sender, EventArgs e)
    {
        ((Control)sender).BackColor = Color.White;
    }

Some label backgrounds change to white, and the same ones don't.

Upvotes: 2

Views: 2159

Answers (3)

RAN
RAN

Reputation: 598

if you really want it to do in the foreach loop:

foreach (Control c in panel1.Controls) {
    if (c.Type ==  typeof(Label)) { //or something like that...
          c.Click += HandleClick;
    }
}

Upvotes: 0

Jay Walker
Jay Walker

Reputation: 4713

Why not just add the handler when you create the label instead of later through a loop over the controls (where you should probably be referencing x instead of label.

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);

Upvotes: 2

Tomtom
Tomtom

Reputation: 9394

Do the

label.Click += Eventhandler;

after you created the label

Upvotes: 0

Related Questions