1

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.

ib11
  • 2,530
  • 3
  • 22
  • 55
  • Why the downvote? I have seen this done, for example here: http://stackoverflow.com/questions/11518529/how-to-call-a-button-click-event-from-another-method And I get it from the answers that this is a bad practice, but this is why I asked in the first place... – ib11 Apr 29 '16 at 23:11

2 Answers2

3

You can put null in event parameter :

linkLabel2_LinkClicked(this, null);

or create a new event object :

linkLabel2_LinkClicked(this, new LinkLabelLinkClickedEventArgs());

But the best way is create a separate methode and call it in every time you need it.

Abdellah OUMGHAR
  • 3,627
  • 1
  • 11
  • 16
2

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();
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • 2
    "It's discouraged", i´m agreeing totally. Calling an EventHandler method directly is bad practise. Furthermore you should use EventHandler Methods only to call functions in your business logic – whymatter Apr 29 '16 at 22:54
  • I changed the code and your answer helped me debug the issue I had. – ib11 Apr 30 '16 at 01:39