C# Call an event (linkLabel2_LinkClicked) from another method - c#

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.

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.

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

Related

How to ask a method to repeat itself from another method

I need Method1 to repeat itself in the Method3. How can i do that?
Code example [edit1]:
namespace NamespaceName
{
public partial class ClassName
{
private void Method1(object sender, EventArgs e)
{
Statement1;
Statement2;
Statement3;
}
public void Method2 (object sender, MouseEventArgs e)
{
//Another bunch of statements
}
private void Method3 (object sender, EventArgs e)
{
"Want to repeat those statements from Method1 without copying them here"
}
}
}
P.S. I'm new to programming and i have no idea what my options are and searching the web didn't helped much either.
Sorry if this question has already been asked and if so, could you please link it here?
Edit1: Well, in attempt to write an abstract example instead of my actual code i omitted the important things. Now it should look more adequate.
Tell me if it is not what you are looking for.
You need only call your method Method1 in your Method3.
private Method3
{
//"Want to repeat those statements from Method1 without copying them here"
//For your sender parameter, assuming that was a button named btn1.
//you can send the btn1 as sender and null as eventargs.
Method1(btn1, null); //Will execute the code in your method1.
}

Is there a better way to initialize EventHandlers in C#

Let's say that I am writing a class library of some sort. I have a class:
public class PopupControl : UserControl {
// Some code
public event EventHandler PopupFinished;
}
If I want to handle this event in another class, I just use the += operator and nothing special happens. However, when the event is not handled anywhere, PopupFinished is null. And when I call PopupFinished (this, EventArgs.Empty), I get a NullReferenceException. So I need to do this:
public PopupControl () {
PopupFinished += popupFinished;
//Some more code
}
private void popupFinished (object sender, EventArgs e) {}
This doesn't sound like a good programming practice though. (or is it?)
Then I thought of another way:
try {
PopupFinished (this, EventArgs.Empty);
} catch (NullReferenceException) {}
But that doesn't sound right either.
Please tell me which of the above is better and whether there is another way to do that. Thanks!
Do a test to check PopupFinished is not null before calling it.
if(PopupFinished != null)
PopupFinished();

Call method without parameters

I have a quick C# question.
I have a list that I need to pass onto a method. So I did this:
Form2 f2 = new Form2(JogadoresList);
f2.novoJogo(JogadoresList);
And on another class:
public void novoJogo(List<Jogadores> JogadoresList)
{}
But now I want to call the novoJogo method from a
private void button1_Click(object sender, EventArgs e)
{
}
method. How can I call the novoJogo method if I don't have parameters to pass onto it and don't want to replace the novoJogo's list? Thank you.
You can just call novoJogo passing null value as parameter:
novoJogo(null);
Or an empty list:
novoJogo(new List<Jogadores>());
Also in the novoJogo method, you could define the List<> as an optional parameter:
public void novoJogo(List<Jogadores> JogadoresList=null)
{}
Then, you can call it without passing the argument in the the click event as I show below:
private void button1_Click(object sender, EventArgs e)
{
novoJogo();
}
Either the method needs the list, or it doesn't. So the fact you are asking this is... troubling.
However, you have a couple options. Just pass null:
private void button1_Click(object sender, EventArgs e)
{
//Hopefully you held onto that reference!
f2.novoJogo(null);
}
Or use default arguments/optional parameters:
public void novoJogo(List<Jogadores> JogadoresList = null)
{}
private void button1_Click(object sender, EventArgs e)
{
//Hopefully you held onto that reference!
f2.novoJogo();
}
In both cases, make sure that novoJogo will be OK with a null list passed to it (NRE is really easy to get here if you weren't careful). And consider if your design makes sense here, if only part of the function needs the list, should that really have been two functions instead of one?
Change the access-level of JogadoresList to public static or internal static so you can access it via button1_click.

How can I know which method called event handler

I have two methods:
private void RvListen_OPT()
private void RvListen_FUT()
On a certain event, both call:
void OnRvMessageReceived(object sender, SigRvMessageEventArgs args)
When OnRvMessageReceived is called, how can I check which of the two methods called it? I know it can be done using the object sender, but I'm not sure how to do it.
If you can edit the SigRvMessageEventArgs class you could add a field to it which you set differently in the two calls.
sender will (usually) give you the object that called the event. It may not because its up to the caller to actually set this.
That said, I"m not sure it should matter. If the call depends on who called it, maybe they need to be setup as separate events... Or, as Jackson mentioned, the args variable could be set to allow the OnRvMessageReceived event can respond to that.
Set sender to a string if you can't change SigRvMessageEventArgs to take an additional property... But the best approach would be to modify SigRvMessageEventArgs if possible.
private void RvListen_OPT()
{
OnRvMessageReceived("RvListn_OPT()", new SigRvMessageEventArgs())
}
private void RvListen_FUT()
{
OnRvMessageReceived("RvListn_FUT()", new SigRvMessageEventArgs())
}
void OnRvMessageReceived(object sender, SigRvMessageEventArgs args)
{
if(sender.ToString() == "RvListn_OPT()"){
// do work
}
else if(sender.ToString() == "RvListn_FUT()"){
// do work
}
}

Calling C# events from outside the owning class?

Is it possible under any set of circumstances to be able to accomplish this?
My current circumstances are this:
public class CustomForm : Form
{
public class CustomGUIElement
{
...
public event MouseEventHandler Click;
// etc, and so forth.
...
}
private List<CustomGUIElement> _elements;
...
public void CustomForm_Click(object sender, MouseEventArgs e)
{
// we might want to call one of the _elements[n].Click in here
// but we can't because we aren't in the same class.
}
}
My first thought was to have a function similar to:
internal enum GUIElementHandlers { Click, ... }
internal void CustomGUIElement::CallHandler(GUIElementHandler h, object[] args) {
switch (h) {
case Click:
this.Click(this, (EventArgs)args[0]);
break;
... // etc and so forth
}
}
It's a horribly ugly kludge, but it should work... There must be a more elegant solution though? The .NET library does this all the time with message handlers and calling events in Control's. Does anyone else have any other/better ideas?
You just need to add a public method for invoking the event. Microsoft already does this for some events such as PerformClick for controls that expose a Click event.
public class CustomGUIElement
{
public void PerformClick()
{
OnClick(EventArgs.Empty);
}
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
Click(this, e);
}
}
You would then do the following inside your example event handler...
public void CustomForm_Click(object sender, MouseEventArgs e)
{
_elements[0].PerformClick();
}
The event keyword in c# modifies the declaration of the delegate. It prevents direct assignment to the delegate (you can only use += and -= on an event), and it prevents invocation of the delegate from outside the class.
So you could alter your code to look like this:
public class CustomGUIElement
{
...
public MouseEventHandler Click;
// etc, and so forth.
...
}
Then you can invoke the event from outside the class like this.
myCustomGUIElement.Click(sender,args);
The drawback is that code using the class can overwrite any registered handlers very easily with code like this:
myCustomGUIElement.Click = null;
which is not allowed if the Click delegate is declared as an event.
You can shorten the code suggested in the accepted answer a lot using the modern syntax feature of the .NET framework:
public event Action<int> RecipeSelected;
public void RaiseRecpeSelected(int recipe) => RecipeSelected?.Invoke(recipe);
You really should wrap the code you want to be able to execute from the outside in a method. That method can then do whatever your event would do - and that event would also instead call that method.

Categories

Resources