How to ask a method to repeat itself from another method - c#

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.
}

Related

How to define an extra parameter in a ClickHandler? [duplicate]

I've been looking for an answer for about an hour on Google but I did not found exactly what I'm looking for.
Basically, I have a static Helper class that helps perform many things I do frequently in my App. In this case, I have a method named "CreateDataContextMenu" that creates a context menu on a given TreeView control.
public static void CreateDataContextMenu(Form parent, TreeView owner, string dataType)
{ ... }
TreeView owner is the control in which I will associate my context menu.
Then later on I add a Click event to a MenuItem like this:
menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click);
The problem I have here is that I want to pass "owner" and "dataType" as arguments to the menuItemFolder_Click event.
I tried the following:
menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click(sender,e,owner,dataType));
(...)
private static void menuItemFolder_Click(object sender, System.EventArgs e, Treeview owner, string dataType)
{...}
But it doesn't work at all. It might be very naive of me to do it that way but I"m not very comfortable with event handler yet.
Any idea on how I could do that?
My first guess is that I need to create my own EventHandler for this specific case. Am I going in the right direction with that?
You should create a lambda expression that calls a method with the extra parameters:
menuItemFolder.Click += (sender, e) => YourMethod(owner, dataType);
Honest admission up front: I have not tried the code below.
I think the reason
menuItemFolder.Click += new System.EventHandler(menuItemFolder_Click(sender,e,owner,dataType));
won't work is because you are actually passing to System.EventHandler () the result of the invocation of menuItemFolder_Click () with the parameters provided. You are not passing a pointer to the function itself.
Try to write another function that implements the details of menuItemFolder_Click (). See if something like
private void menuItemFolder_Click_Helper (object sender, EventArgs e, object Owner, object DataType) {
// implement details here
}
and then call the function from within menuItemFolder_Click ().
I think the simplest code would be this:
EventHandler myEvent = (sender, e) => MyMethod(myParameter);//my delegate
myButton.Click += myEvent;//suscribe
private void MyMethod(MyParameterType myParameter)
{
//Do something
//if only one time
myButton.Click -= myEvent;//unsuscribe
}
Passing custom args into an event handler is not too difficult. Below is a clean and easily reusable method of doing so. Check it:
public class MyClass
{
public CustomArgsEventHandler MyEvent1;
public MyClass(){MyEvent1+=observer;}
public void observer(object sender, CustomEventArgs e){print(e.myArg);}
//...
}
//place in the same file if you like!
public class CustomEventArgs : EventArgs
{
public float myArg {get;set;}
public CustomEventArgs (float d) { myArg = d; }
}
public delegate void CustomArgsEventHandler (object sender, CustomEventArgs e);

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

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.

Control.PerformClick() isn't doing anything, what am I missing?

I've reviewed the MSDN doc and a couple SO answers, and all signs point to this working. At this point, I think I've either completely misunderstood what to expect or I've missed one line of code I need.
In short, I've got a WinForms app with a button, and I want another function to "click" that button at one point in the code. Here's the relevant bits:
// form.Designer.cs
this.btnAddBranch.Click += new System.EventHandler(this.btn_add_Click);
// form.cs
// using statements
public partial class EditClient : Form
{
// ...
public TestClick()
{
//btnAddBranch.PerformClick(); <-- would like to know why this fails ...
btn_add_Click(this, EventArgs.Empty);
}
private void btn_add_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked it!");
}
}
The commented line for btnAddBranch.PerformClick() is what I was hoping would do the equivalent of the line below it. But it doesn't, it doesn't seem to do anything when TestClick() is called. If I do the uncommented line, it works fine.
Am I missing something, or am I totally misunderstanding something?
Your problem is that TestClick() is your form constructor. There are no Controls to call PerformClick() on until the Form Constructor is complete. If you really want to call the code that early then do something like the following.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Do not call methods on controls here, the controls are not yet initialized
}
private void TestClick()
{
btn_add.PerformClick();
}
private void btn_add_Click(object sender, EventArgs e)
{
MessageBox.Show("You Clicked it");
}
private void Form1_Load(object sender, EventArgs e)
{
TestClick();
}
}
Calling your PerformClick() anywhere other than the form constructor will create the desired results.
Sorry, I've updated my answer to correct it. I initially thought it was because you were not calling Button.PerformClick() after Form.InitializeComponent() (from the Form.Designer.cs auto-generated code), but I was corrected that this still does not work.
It seems that the Form is not sufficiently created in the constructor to allow Button.PerformClick(). I theorized that this may due to the fact that the Modal message loop wasn't fully created yet, but after looking at Button.PerformClick's code in Reflector, that doesn't seem to be quite the case.
PerformClick's code looks like this:
public void PerformClick()
{
if (base.CanSelect)
{
bool flag;
bool flag2 = base.ValidateActiveControl(out flag);
if (!base.ValidationCancelled && (flag2 || flag))
{
base.ResetFlagsandPaint();
this.OnClick(EventArgs.Empty);
}
}
}
While looking through, the first failure I notice here is CanSelect will return false because the control is not currently Visible (ShowDialog has not yet been called). Therefore, PerformClick will do nothing as observed. This is by digging down through the CanSelect implementation:
internal virtual bool CanSelectCore()
{
if ((this.controlStyle & ControlStyles.Selectable) != ControlStyles.Selectable)
{
return false;
}
for (Control control = this; control != null; control = control.parent)
{
if (!control.Enabled || !control.Visible)
{
return false;
}
}
return true;
}
In the debugger, you can put a breakpoint in the constructor and see that Button1 will not yet be visible (makes sense).
However, I will suggest that you can accomplish what you want from the constructor, by separating your application logic from the Button's event handler. For example...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DoSomething();
}
private void DoSomething()
{
// application logic here...
MessageBox.Show("Hello World");
}
private void button1_Click(object sender, EventArgs e)
{
DoSomething();
}
}
Or, as the previous answer suggests you can call Button.PerformClick() from the Form.OnLoad method. However, it is probably better to just call the application logic directly from both spots instead of performing button clicks in the UI.
Sorry for the initially incorrect answer. Hope this helps explain.
Make sure your form is already Shown :)
If its hidden, or not shown, you cant perform a click.
Atleast this way it worked for me (i show a form for a short moment, perform a click, and hide it immidiately after).
And it works!

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

Categories

Resources