ShoaibSivany ShoaibSivany - 26 days ago 6
C# Question

How to access object's Click Event through code

I made a class of label class label

class label
{
public Label l;
public Label acess()
{
l = new Label();
l.Text = "asdad";
l.Left=100;
l.Top =100;
return l;
}
public Label lab
{
get
{
return l;
}
set
{
l = value;
}
}

}


And called this method and initialized it on the form

Label l;
label cls;
public MainForm()
{

InitializeComponent();




cls = new label();
l = new Label();
l =cls.acess();
this.Controls.Add(l);

}


Now i can access my label("l") ".Click" option through "lab" like

cls.lab.Click = //anything


but i dont know how to use this statement, i just knew how to use click events going through the label events, but i dont know how to use this one(which made through the code).
How can i use it if i want to check label's text, like

cls.lab.Click = {

if(lab.text=="i am the old label")
{
lab.text = "i am the new label";
}
}


Please Explain Me, Give a Detailed Answer.

Answer

You add an event listener to the label like this:

public MainForm()
{
    InitializeComponent();

    cls = new label();
    l =cls.acess();
    l.Click += cls_Clicked;
    this.Controls.Add(l);
}

private void cls_Click(object sender, EventArgs e)
{
    Label clickedLabel = sender as Label;
    if(clickedLabel == null) return;

    if(clickedLabel.Text=="i am the old label")
    {
        clickedLabel.Text = "i am the new label";
    }
}

I wasn't able to test it right now, but it should work, assuming you are using WinForms.