Search code examples
c#winformseventhandlerlinklabel

C# Call an event (linkLabel2_LinkClicked) from another method


I have an event handler on my form for a LinkLabel linkLabel2_LinkClicked:

private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    //code here
}

I need to call it from another method that does not have an object sender and any eventargs:

private void UpdateMethod()
{
    linkLabel2_LinkClicked(this, ?????)
}

If it were a Button I would just call the PerformClick method. But there is no such for a LinkLabel that I could find.

What is the best practice to execute the code in the linkLabel2_LinkClicked event handler?

Update: I guess I was not clear on this. I wonder about the best practice as I have seen this approach. I can see from the answers that this is not the correct approach but to move the code to a separate method and call it directly from the other method. Please let me know if any other reasoning goes with this.

Update 2: I rewrote the code now as follows:

private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    CreatePreview();
}

private void UpdateMethod()
{
    CreatePreview();
}

private void CreatePreview()
{
    //code comes here
}

It works perfectly.


Solution

  • You could just pass null since you're not using the parameter anyway, but I'd recommend against that. It's discouraged to call an event directly, and it leads to code that's tough to read.

    Just have the other method call CreatePreview().

    private void UpdateMethod()
    {
        CreatePreview();
    }