How to call common Method to multiple Events - c#

Hello I have this code:
private void txtNumero_KeyDown(object sender, KeyEventArgs e)
{
CercaCliente();
}
private void txtNote_KeyDown(object sender, KeyEventArgs e)
{
CercaCliente();
}
private void txtNominativo_KeyDown(object sender, KeyEventArgs e)
{
CercaCliente();
}
How can I write this code in better mode? Thanks

there are two approaches you can choose from, and it depends what type of effort you are ready to do...
first when you bind the event there itself call the method rather than creating handler method for each.
Currently, you are doing -
txtNumero.KeyDown += new txtNumero_KeyDown;
..
..
txtNote.KeyDown += new txtNumero_KeyDown;
then in your method you are calling this common method 'CercaCliente()'. you can directly use func delegate to call you common method. e.g.
txtNumero.KeyDown += (o,e)=>CercaCliente();
..
..
txtNote.KeyDown += (o, e)=>CercaCliente();
OR
You can create custom control, derived from textbox, and there you can handle it.

Add this common method
private void HandlerMethod(object sender, EventArgs e)
{
CercaCliente();
}
Then inside your form load Attach this handler method to all events
this.txtNominativo.KeyDown += HandlerMethod;
this.txtNote.KeyDown += HandlerMethod;
this.txtNumero.KeyDown += HandlerMethod;

Related

Can I have a have a void inside an event handler declaration?

I have a button on my C# Winform, and the following code:
button1.Click += button1_Click;
and also:
private static void button1_Click(object sender, EventArgs e)
{
// do something
}
I am trying to simplify and reduce the amount of code in my application. Is there any way to do this?
Here's what I am trying to achieve:
button1.Click += void button1_Click(object sender, EventArgs e)
{
// do something
};
This does not work. Is there any other way to achieve this?
You can do this with an anonymous method:
button1.Click += (sender, e) =>
{
// do something
};
But note that you will never be able to unregister this event handler as it is an anonymous method.

Adding event to button programmatically

I want to add an event to a programmatically generated button like this:
Button activityButton = new Button();
activityButton.Click += new EventHandler(onChangeActivityFilter);
I'm getting the following exception in the 2nd line:
Cannot implicit convert type System.EventHandler to System.Windows.RoutedEventhandler
The onChangeActivityFilter methode looks like this:
private void onChangeActivityFilter(object sender, EventArgs e)
{
}
I'd like to know what I'm doing wrong.
You need to create a instance of RoutedEventHandler:
activityButton.Click += new RoutedEventhandler(onChangeActivityFilter);
And also change the method signature:
private void onChangeActivityFilter(object sender, RoutedEventArgs e)
{
}
RoutedEvents where introduced with WPF.
You can also use lambda functions
activityButton.Click += (sender, e) =>
{
MessageBox.Show("the button was clicked");
};

Action when Form is closed c#

I'm in College and this is my first (major) project.
I'm trying to perform an action when a form is closed. I don't seem to be getting the terminology right when searching online, or the answer given doesn't match what I want to do.
At the moment i'm declaring a Class and displaying the from -
private void createuser_Click(object sender, EventArgs e)
{
User_Modification mod = new User_Modification("Create", "Create");
mod.ShowDialog();
}
What I want to do is this -
WHEN mod IS CLOSED {
// Do stuff
}
You're using ShowDialog, so the code following it is not executed until after the dialog box is closed. mod.ShowDialog(); doStuff(); will work pretty well.
You need to create a handler to capture the FormClosed event:
In your constructor do:
this.FormClosed += Form_Closed;
Then in the body of your form, add this method.
private void Form_Closed(object sender, FormClosedEventArgs e)
{
// Do stuff
}
You should attach handler to FormClosed event:
private void createuser_Click(object sender, EventArgs e)
{
User_Modification mod = new User_Modification("Create", "Create");
mod.FormClosed += new FormClosedEventHandler(FormClosed);
mod.ShowDialog();
}
void FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Closed");
}
if you're using WinForms you can override OnFormClosing event:
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
// your code...
}
You'll want to take a look at two events:
Form.FormClosing : https://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing(v=vs.110).aspx
Form.FormClosed : https://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed%28v=vs.110%29.aspx
First one will allow you to perform actions prior to the form being closed completely, such as canceling the closing procedure. The second one is what you would use if you want to perform actions after the form is closed (perhaps to clean up resources, as an example).
So, as an example, let's say that you want to perform an action when the form is in fact closed:
// Somewhere in your code where you create the form object.
form.FormClosed += Form_FormClosed;
// Somewhere else in your code.
private void Form_FormClosed(Object sender, FormClosedEventArgs e)
{
MessageBox.Show("Form closed");
}

How to call treeView.SelectedItemChanged programmatically

In my program I would like to call to a SelectedItemChanged event using c# code-behind, I am just unsure about what to pass as parameters. This is for a TreeViewItem.
//Gets selected item in TreeView
private void TreeOne_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
MainWindowViewModel.SelectedItem = e.NewValue as TreeViewItem;
}
//I'm calling the SelectedItemChanged event from a RightButtonDown event
private void TreeOne_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
TreeOne_SelectedItemChanged(/* What would go here? **/);
}
Also, when I try to build this I receive this compiler error that pretty much led to this question...
No overload for method TreeOne_SelectedItemChanged takes '0' arguments
I'm hoping that this is an easy question, but if I have not provided enough information, or haven't been clear enough please let me know.
Adding to #Bart Friederichs' answer and assuming that you have a reference to your TreeView, you could add the following method:
private void SetSelectedItem()
{
MainWindowViewModel.SelectedItem = TreeOne.SelectedItem;
}
Then you can simply call this from wherever you like:
private void TreeOne_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
SetSelectedItem();
}
private void TreeOne_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
SetSelectedItem();
}
The usual design pattern would be to call some kind of processing method, and not to "manually" fire events:
private TreeOne_SelectedItemChaned(object sender,
RoutedPropertyChangedEventArgs<object> e) {
processChange();
}
Then, from withing your code, you just call processChange(), no need to call TreeOne_SelectedItemChanged.
try to call
TreeOne_SelectedItemChanged(null, null);

Trigger control's event programmatically

Assume that I have a WinFoms project. There is just one button (e.g. button1).
The question is: is it possible to trigger the ButtonClicked event via code without really clicking it?
Button controls have a PerformClick() method that you can call.
button1.PerformClick();
The .NET framework uses a pattern where for every event X there is a method protected void OnX(EventArgs e) {} that raises event X. See this Msdn article. To raise an event from outside the declaring class you will have to derive the class and add a public wrapper method. In the case of Button it would look like this:
class MyButton : System.Windows.Forms.Button
{
public void ProgrammaticClick(EventArgs e)
{
base.OnClick(e);
}
}
You can just call the event handler function directly and specify null for the sender and EventArgs.Empty for the arguments.
void ButtonClicked(object sender, EventArgs e)
{
// do stuff
}
// Somewhere else in your code:
button1.Click += new EventHandler(ButtonClicked);
// call the event handler directly:
ButtonClicked(button1, EventArgs.Empty);
Or, rather, you'd move the logic out of the ButtonClicked event into its own function, and then your event handler and the other code you have would in turn call the new function.
void StuffThatHappensOnButtonClick()
{
// do stuff
}
void ButtonClicked(object sender, EventArgs e)
{
StuffThatHappensOnButtonClick();
}
// Somewhere else in your code:
button1.Click += new EventHandler(ButtonClicked);
// Simulate the button click:
StuffThatHappensOnButtonClick();
The latter method has the advantage of letting you separate your business and UI logic. You really should never have any business logic in your control event handlers.
Yes, just call the method the way you would call any other. For example:
private void btnSayHello_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World!");
}
private void btnTriggerHello_Click(object sender, EventArgs e)
{
btnSayHello_Click(null, null);
}
button1.PerformClick();
But if you have to do something like this maybe it's better to move the code you have under the event on a new method ?
Why don't you just put your event code into a Method. Then have the Event execute the method. This way if you need to execute the same code that the Event rises, you can, but simply just calling the "Method".
void Event_Method()
{
//Put Event code here.
MessageBox.Show("Hello!");
}
void _btnSend_Click(object sender, EventArgs e)
{
Event_Method();
}
void AnotherMethod()
{
Event_Method();
}
Make sense? Now the "Click" event AND anywhere in code you can trigger the same code as the "Click" event.
Don't trigger the event, call the method that the event calls. ;)
In most cases you would not need to do that. Simply wrap your functionality in functions related to a specific purpose (task). You call this function inside your event and anywhere else it's needed.
Overthink your approach.
I recently had this problem where I wanted to programatically click a button that had multiple event handlers assigned to it (think UserControl or derived classes).
For example:
myButton.Click += ButtonClicked1
myButton.Click += ButtonClicked2;
void ButtonClicked1(object sender, EventArgs e)
{
Console.WriteLine("ButtonClicked1");
}
void ButtonClicked2(object sender, EventArgs e)
{
Console.WriteLine("ButtonClicked1");
}
When you click the button, both functions will get called. In the instances where you want to programmatically fire an event handler for a function from a form (for example, when a user presses enter in a Text field then call the InvokeOnClick method passing through the control you. For example
this.InvokeOnClick(myButton, EventArgs.Empty);
Where this is the Form instance you are in.
use a for loop to call the button_click event
private void btnadd_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i <= 2; i++)
StuffThatHappensOnButtonClick();
}
void StuffThatHappensOnButtonClick()
{
........do stuff
}
we assume at least one time you need click the button

Categories