call an event from another event in c# - c#

I have a question when programing in c#. I want to call an event from another event like this.
private void button1_Click(object sender, EventArgs e)
{
Form2 formulario = new Form2();
formulario.ShowDialog();
// here i call an event from the second form. that event is radiobutton_checkedchange
formulario.radioButton1_CheckedChanged(sender, e);
The problem is that i look everyware how to solve this problem... They said me that an event is like a method but i think is not the same, because when i call that event like a method it looks like i call it just once. The event dont recognize the checked change.
am I wrong ? is this posible in c#. Thanks to all, i'm new in programing with events. And sorry for my bad english

First, radioButton1_CheckedChanged is not an event, it is probably an event handler. In the end, it is still a method like all others.
You shouldn't directly call the event handler of an event, just create another method and what the call there. Put this in your Form2:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{ // private, only accessible from the class itself
this.SetState();
}
public void SetState()
{ // public, accessible from anywhere
// put your original code from radioButton1_CheckedChanged here
}
In that way, you don't have to call event specific code, but you can write that away in a separate method, which is easier to use and clearer in its purpose.
If both forms share the same data object / view model, you can set the value from there. That would be better from a OOP perspective. Look into MVVM or MVC for good design patterns to do so.

It sounds like you have logic in radioButton1_CheckedChanged that you also want to call when the button is clicked. If that's the case, then move the common logic to a new method and call it from both places.
If you want to change the checked status of radioButton1 then just change its status. Event hnadlers respond to UI changes, they do not generate them.

Related

xamarin.forms - how to have two views' event handlers call same code

I have two views, say one for tablet, one for phone. They have both an Entry field and they use same functionality, layout is the only difference.
I want to remove code duplication and since both Entry fields have identical logic inside OnTextChanged, i would like to move it to another method that both these Entry events can call.
How to make both Entrys OnTextChanged event call same centralized method?
What would be best way to do that in Xamarin Forms?
As mentioned by #SLaks , it sounds like your best approach is to us MVVM. There is a lot of information about MVVM online.
The super simple approach for implementing one method into two events is below:
// Handler for the first Entry
private void Entry1_TextChanged(object s, TextChangedEventArgs e)
{
HandleTheTextChanged(e.NewText);
}
// Handler for the second Entry
private void Entry2_TextChanged(object s, TextChangedEventArgs e)
{
HandleTheTextChanged(e.NewText);
}
// Common code
private void HandleTheTextChanged(string newText)
{
// Do your stuff
}

Fire an event within another event

I need help on firing an event within C#
Basically I have a onclick event that fires when you click on a checkbox
void OnClick(object sender, RoutedEventArgs e)
{
...
}
I need help on firing an event within C#
Basically I have a onclick event that fires when you click on a checkbox
void OnClick(object sender, RoutedEventArgs e)
{
...
}
However, I need to fire this event once another event has been fired, so within this new event, is it possible I can fire the above one?
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
switch(dataGrid.Name)
{
case "Customer"
//fire OnCLick Event
break;
}
}
I have tried something like
??? += new MouseEventHandler(OnClick);
But I am not sure if this will actually work.
Yes you can, but only if the event is in your own class. You can't even raise a base class' event. You have a put a method in the base class to raise the event, and then call that.
The code you put there is adding another event handler, not raising an event; you don't need to do that.
If it's a button, use btnDoSomething.PerformClickEvent (winforms)
If the handler is in your code, you can call it without raising the event (commenters assume that this is what you want to do but in reaslity there are many cases where you'd need more than this) btnDoSomething_Click(null, null) - null usually works because handler code rarely cares about the sender or arguments and if you don't reference them, you don't need them.
If you can use #4, you can also refactor as mentioned. Usually not needed. But usually so easy to do you it's worth doing for clarity anyway.
For objects that map from Windows widgets of anysort, check out the SendMessage and PostMessage API calls. Wayyyy beyond the scope of this answer, though. Doesn't apply to non-windows-backed objects (but your sample implies windows).

Determine if an Event Handler Method is wired to an Event?

I'm not sure if it's a good idea, and this is probably going to end up as more of an academic exercise, so bear with me:
Let's say I was making a UserControl (as I am), that will every X seconds (using a Timer) look for a text file and display that information within this UserControl. Let's call this control MyUserControl.
To rehash the basic:
I would have this Timer as a member variable of this control, and have code that looks like:
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
And an event handler method that looks like this:
private void timer1_Tick(object sender, EventArgs e)
{
// Read text-file and do lots of goodness.
}
Cool, so now I can set a public property of MyUserControl to some elapsed time, and just by plopping this control on my Form, I have a nice little control updating itself. Neat.
Here's the thing that got me curious:
The Form I'm going to plop it on already has a Timer. So why have two competing timers? I'd love for there to be a way for MyUserControl to only use it's internal timer if it's needed (for example, plopping it on another Form that doesn't already have a Timer).
I suppose I can make the MyUserControl timer1_Tick public like this here:
public void timer1_Tick(object sender, EventArgs e)
{
// Read text-file and do lots of goodness.
}
And then, because these things are multicast, do something like this here in the form:
this.theFormTimer.Tick += new System.EventHandler(this.theFormTimer_Tick);
this.theFormTimer.Tick += new System.EventHandler(MyUserControlObject.timer1_Tick);
And also set a member variable of MyUserControl to not enable itself.
But is there some slicker way of doing this? Can I determine somehow that the event handler method in MyUserControl was already wired to the Form Timer's tick event? Or use some other type of approach than what I'm suggesting?
Thanks! (apologies if this ends up being a duplicate, my google-fu may be bad today)
Not discussing if you should or shouldn't do this, but to answer the question, I'd do it this way:
//add a handler
timer.Tick += timer_tick;
//...
//check if timer_tick is wired to Tick
if (timer.Tick.GetInvocationList().Contains (timer_tick))
{
//do something
}
I haven't tested it, but that's what I'd try.

Setting a "click" method to execute right away

I have a working method
something_Click(object sender, EventArgs e)
{
code
}
...
It of course executes after someone clicks the element. What I need to do is, to execute this method immediately after the element appears on the screen (it is StripStatusLabel). I have tried just to add a call of the method to beginning of the code, but it did nothing.
You can call Button.PerformClick on your button in a Form.Load event handler.
You might also want to consider moving that logic into its own method, and call that method from both the button handler and the Load event, as this will be more clear. (It's obviously code you want triggered on more than just a "button click").
Depending on what framework you are targeting (WPF vs Winforms) you might be able to handle the Load event instead. It triggers when the element appears on screen.
It's not best practice to fire a form event which would normally be originated from teh user. In the sense, you are trying to "fake" the click. Think of the future debugging, or of the colleague who might inherit your project. When inspecting code you would expect something_Click to only be fired when there is a click on "something".
A better solution is to put the "code" part in your snip into a method whose name reflects what it really does.
They you may fire this method in different areas. Fire it at the click, at the load, anywhere.
something_Click(object sender, EventArgs e)
{
DoStuff();
}
OnAppearToScreen()
{
DoStuff();
}
DoStuff()
{
//code that actually does stuff
}
Later on, when you want to check when "the stuff" was done to your object, you can easily tell by code inspection.

Determine how an application is closed

I am trying to determine if my application is closed through clicking the "X" on the windows form, or if they clicked an "Exit" button I have on it. Right now I am using StackTrace.GetFrame(someIndex) to determine how, but i am looking for a more definitive way since it looks like these frame orders arent guaranteed. Is there a better way to make the distinction? This is a .NET 3.5 WinForm, and Im writing in C#.
Use a different event to handle your own "Exit" button click. In your own "Exit" event handler do your extra logic, or set some state variable, and then call the normal application close method.
Post some samples of how your events are wired up and I get give a more specific example. In general it would look something like this:
private void btnMyExit_Click(object sender, EventArgs e)
{
// TODO: add any special logic you want to execute when they click your own "Exit" button
doCustomExitWork();
}
public static void OnAppExit(object sender, EventArgs e)
{
doCustomExitWork();
}
private void doCustomExitWork()
{
// TODO: add any logic you want to always do when exiting the app, omit this whole method if you don't need it
}
Use the FormClosing event and query the FormClosingEventArgs for the enum CloseReason value.

Categories

Resources