I am still trying to learn about c#, my question is how would I pass a variable from Item1_Click to Item2_Click, is this the same thing as passing them between methods or is this different because they are event handlers?
public partial class Events : System.Web.UI.UserControl
{
protected void Item1_Click(object sender, EventArgs e)
{
//code
}
protected void Item2_Click(object sender, EventArgs e)
{
//code
}
}
They are still regular methods, so you're still able to call them the same way you normally would.
protected void Item1_Click(object sender, EventArgs e)
{
// Call the event handler for Item2, passing the arguments
// Item1 received
Item2_Click(sender, e);
}
protected void Item2_Click(object sender, EventArgs e)
{
// Make it happen.
}
If you want to re-use Item1_Click just bind the click event of the other object to Item1_Click as well.
See the links below for some more information on events in C#.
MSDN Event Tutorial
MSDN C# Programming Guide (Events)
Event handlers are called by the publisher of the event. So you'd need to cache the value in a member variable if both handlers are in the same type. Item1 click caches something (e.g. the selection in a variable) and Item2 click uses this member variable for its own handling.
However nothing stops you from calling the event-handler#2 from event-handler#1 ; since it is a method after all. In this case, you could slot in the parameter in the EventHandler argument but it is a bit non-intuitive.
What you've shown above, is a method. It's just that I imagine you've subscribed your methods to events on a couple of buttons.
It is then up to the buttons to populate the EventArgs instances themselves. If you wish to alter what goes into an EventArgs then you'd need to inherit from a Button and override the OnClick method to fire the event manually.
You could have some state information on your form (if you want shared information between the two methods). Or if you're literally wanting to pass information from Item1_Click to Item2_click then you can just call:
protected void Item1_Click(object sender, EventArgs e)
{
this.Item2_Click(sender new EventArgs()); // <== Stick information in EventArgs
}
If you want to preserve some value from a first click you can set a variable and read it from your other handler.
public partial class Events : System.Web.UI.UserControl
{
private SomeType variable;
protected void Item1_Click(object sender, EventArgs e)
{
variable = someValue;
//code
}
protected void Item2_Click(object sender, EventArgs e)
{
//code + do stuff with variable
}
}
Event handlers are methods themselves, so no difference there. Sending data (variables if you will) between methods is done through parameters, however, Event handlers are required to have a specific signature, so you can't just add more parameters. The way to go here is to use a class member (field or property) as some sort of "global variable" (global to the class) as mentioned in #Zebi's answer
Hope this helps :)
An event handler is just a method, that is called in some specific scenario. There's nothing to prevent you from explicitlly calling those methods, so
protected void Item1_Click(object sender, EventArgs e)
{
Item2_Click(sender, e); //pass the original arguments
Item2_Click(null, null); //pass some other arguments
Item1_Click(null, null); //recursively call the handler.
}
is perfectly valid C# code. However, it's a bad practice to use event handler for anything else than, basically handling the event. If two handlers need to use some same logic, it's better to do:
protected void Item1_Click(object sender, EventArgs e)
{
CommonLogic();
}
protected void Item2_Click(object sender, EventArgs e)
{
CommonLogic();
}
private void CommonLogic()
{
//the common logic goes here
}
Instead of calling your event handler directly, you might want to create methods that wrap the functionality of Item1_Click and Item2_Click. For example..
public partial class Events : System.Web.UI.UserControl
{
protected void Item1_Click(object sender, EventArgs e)
{
var theParam = GetParamValue();
//code
Item1Method(theParam);
}
protected void Item2_Click(object sender, EventArgs e)
{
Item2Method();
}
private void Item1Method(object param1)
{
// Item 1 code goes here...
}
private void Item2Method()
{
//item 2 code goes here...
// then call Item1Method
var param2 = GetParamValue();
Item1Method(param2);
}
}
This is just an example of how to avoid calling your event handlers. Doing this will make your code more maintainable down the road.
In addition, now you don't have to worry about providing a sender and Event Args as parameters when trying to run the functionality in Item1_Click
Related
Can't seem to get this to work not sure why.
Have this on one of my classes:
public event Action CloseWindowEvent = delegate { };
private void Close()
{
CloseWindowEvent();
}
On another class i'm subscribed:
remarkViewModel.CloseWindowEvent += CloseRequested;
The method never gets called:
private void CloseRequested()
{
dialog.CloseDetailDialog();
}
Thank you.
Can you check the code where the Call to Close() method happens. I dont see any theoretical error in your code. See it works on a simplified model:
It's definitely being called. Here's a snapshot of the event being raised.
In C #, events must be invoked, and in addition, they have two predefined parameters:
object sender and EventArgs e
Here this keyword refers to the object that triggers the event and EventArgs.Empty sends empty arguments to that event, you can also instantiate the class by replacing EventArgs.Empty with new EventArgs
public event EventHandler CloseWindowEvent;
private void CloseEvent()
{
CloseWindowEvent?.Invoke(this, EventArgs.Empty);
}
where
remarkViewModel.CloseWindowEvent += CloseRequested;
private void CloseRequested(object sender, EventArgs e)
{
}
I would like to call an event having parameters from another event, both have different namespaces, is it passable to do this?
public void event1(object1 sender, eventArgs e1)
{
// code goes here
}
public void event2(object2 sender, eventArgs e2)
{
// here I want call event1 with parametersenter code here
}
is it possible?
The best way to do this is not in terms of events being called but just methods being called.
If in the simplest terms your events just called Method1 and Method2 respectively then you could easily have Method1 call Method2 and do whatever it does.
You could raise potentially raise event1 from inside event2 but it doesn't necessarily make sense to do so (for example if it is a click event it should only be raised by a click. It is best to just refactor common code into a method that can be easily called using standard OOP techniques. In my code below I've made the extracted methods static methods so they are easier to call from other objects and assumed that Method1 is in Class1 (not explicitly shown) which is in Namespace1. You may need to do things slightly differently if you need them to be non-static methods.
Here's the example of what I mean.
public void event1(object1 sender, eventArgs e1)
{
var myParameter = ...;
Method1(myParameter);
}
public static void Method1(object myParameter)
{
// code goes here
}
public void event2(object2 sender, eventArgs e2)
{
var myParameter = ...;
Method2(myParameter);
}
public static void Method2(object myParameter)
{
Namespace1.Class1.Method1(myParameter);
}
Using "MyNameSpace";
thats all you need.
I need to write 30 characters so
include "mynamespace" for c++.
Unless i misunderstood what you meant.
I have the following method that is called when ListView item selection is changed:
private void SlideTransitionsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
.........
}
I would like to call this method from some other method. How would I do that?
That is an event handler. It's fired on UI actions. Calling it directly isn't a great idea. Put a method inside it, and then you can call that method if you need to from other places.
private void SlideTransitionsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DoSomeStuffOnSelectionChanged();
}
public void DoSomeStuffOnSelectionChanged()
{
// enter code here
}
Extract all code from SlideTransitionsList_SelectionChanged handler to other method and call it.
private void SlideTransitionsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DoSmth();
}
...
private void OtherMethod()
{
DoSmth();
}
If the paramters of sender and e are not used, simply call the method directly from any other method.
SlideTransitionsList_SelectionChanged(null, null);
Note that you are not firing off an event by calling this method; this is just the event's callback method and can be used by any other method.
The advice given in the other answers are just as correct, but are simply syntatic suger for coding paradigms and can be used as preference or styles are dictated.
I am trying to fire the Button Click event without clicking the actual button. Is there a way to invoke that? I want to call the Cancel event and here is what I have so far:
protected void Cancel(object sender, EventArgs e)
{
this.BindGridView();
}
Since all you have is this.BindGridView(), which I am assuming is just another method, you can just call that instead.
However, if you wanted to do more than just that, what I usually do is create methods for all my events in the form of OnXxx and call that from the event handler.
So for your example, you would create an OnCancel method:
private void OnCancel()
{
this.BindGridView();
}
... and then in your event handler:
protected void Cancel(object sender, EventArgs e)
{
this.OnCancel();
}
Doing this allows your event to trigger naturally and still function as well as allowing you the ability to call the same thing from anywhere within your code via this.OnCancel().
You can call the cancel method directly from within the same object:
Cancel(null,null)
Server side I've done it like this:
private void Page_Load(object sender, EventArgs e)
{
//Do something
Cancel(sender, e);
}
I've been wondering this for a while now; but especially more so since I've been more focused on front-end development for the last few weeks. It might sound like a broad question, but hopefully there's an answer, or a reason as to:
Why aren't .NET web control event handlers generic?
Reasoning
The reason I ask, is due to the nicety and elegance of strongly typed event handlers. Throughout my project, wherever required, I tend to use the .NET generic EventHandler<T> delegate, which has been around since .NET 2.0; as discussed here.
public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs
It would be relatively straight forward to expand on this, and to define a type for the sender as well, something like so.
public delegate void EventHandler<TSender, TArgs>(TSender sender, TArgs args) where TArgs : EventArgs
Whenever working with .NET controls, occassionally I find myself binding the event handler in the code-behind rather than the ASPX file, and then having to cast the object to the desired type if I need to do any additional checks or alterations.
Existing
Definition
public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
public event EventHandler Click;
}
Implementation
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.MyButton.Click += new EventHandler(MyButton_Click);
}
protected void MyButton_Click(object sender, EventArgs e)
{
// type cast and do whatever we need to do...
Button myButton = sender as Button;
}
Generic
Definition
public class Button : WebControl, IButtonControl, IPostBackEventHandler
{
public event EventHandler<Button, EventArgs> Click;
}
Implementation
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.MyButton.Click += new EventHandler(MyButton_Click);
}
protected void MyButton_Click(Button sender, EventArgs e)
{
// no need to type cast, yay!
}
I know it's a relatively small change, but surely it's more elegant? :)
Because it's old.
The web controls were developed for .NET 1.0, and generics didn't arrive until .NET 2.0.
Of course the controls could have been changed, but that means that all old code would need to be changed to compile (and they would need to be recompiled as the old binaries wouldn't work any more), and all old examples (millions of web pages) would be obsolete.