What do sender and eventArgs mean/refer to? How can I make use of them (for the scenario below)?
Scenario:
I'm trying to build a custom control with a delete function, and I want to be able to delete the control that was clicked on a page that contains many of the same custom control.
The sender is the control that the action is for (say OnClick, it's the button).
The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.
What Chris is saying is you can do this:
protected void someButton_Click (object sender, EventArgs ea)
{
Button someButton = sender as Button;
if(someButton != null)
{
someButton.Text = "I was clicked!";
}
}
sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:
private void myCustomControl_Click(object sender, EventArgs e)
{
((MyCustomControl)sender).DoWhatever();
}
The 'sender' is just the object that was actioned (eg clicked).
The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.
'sender' is called object which has some action perform on some
control
'event' its having some information about control which has
some behavoiur and identity perform
by some user.when action will
generate by occuring for event add
it keep within array is called event
agrs
FYI, sender and e are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
Related
I'm working on a project and I'm in a situation where the administrator needs to accept new users into the system. I've got a form that only admins can access, which shows a list of all the waiting applicants. I've found out how to create buttons at run time and how to add an event handler for the click event, but the handler requires a method by the same name to run.
Obviously I can't just put code for a method inside a for loop, unless I'm mistaken. How would I give the program the ability to support an potentially infinite amount of applicants?
void AcceptUsersAdminLoad(object sender, EventArgs e)
{
//FOR LOOP - To be finished. Will read an xml file to find out # to loop.
Button newButton = new Button();
newButton.Click += new System.EventHandler(newButtonClick);
newButton.Text = "Accept";
Panel1.Controls.Add(newButton);
}
private void newButtonClick (Object sender, System.EventArgs e){
}
This works, but as I've said, only for one button. As relatively painless as it would be to copy the method and append it's name with a number a hundred times, I'd prefer to find a way with support for more.
You can use that same method for all of your buttons! The sender parameter will tell you which button is the source, simply cast it to a button. You can store an ID of some sort in the .Tag() property of the button so you know who you are working with (when you create them, assign it).
private void newButtonClick (Object sender, System.EventArgs e){
Button btn = (Button)sender;
// ... do something with "btn" in here ...
}
Answer to the titular question: You don't create methods in a loop. You will occasionally create anonymous methods in a loop, but save that for later :).
To do what you want though: When you generate these buttons, they should all be pointing to the same event handler. The logic you want to run is the same, but the data is different.
How you get the data to the function is not trivial, one (hackish) way to do it is to store the related object (or its index) in the Tag property of the button, which you can then retrieve via the sender argument of the event handler.
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).
In My VB.NET web page, I have this standard event. Note the "Handles" clause on teh event declaration.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
In my C# web app, I have this:
protected void Page_Load(object sender, System.EventArgs e)
{
Since C# doesn't have a "Handles" equivalent and from what I've seen, event handlers are wired up using delegate += syntax, I was looking for this, but I could not foind it in the aspx page, aspx.cs file or the aspx.designer.cs file.
In VB, I would have two drop down lists at the top of the Code Editor window and I could select any object on the web form or the web form itself and see the possible events for the object. Selecting the event would either take me to the event handler or if it didn't exists, it would create the stub for me.
I know that the Properties window in C# (and I think in VB, too) has an Event tab that shows the list of events for the selected object GUI object, but "Page" doesn't appear as an object that can be selected.
Where does C# define the hooking up of the event to the handler?
How do I generate a stub for the Page event handler routine? I know that the handle appears by default, but what if it is deleted or I want to add a Page_initialize code? Is there an easy way to get the stub or do I need to go to the Object Browser for the syntax?
In C# web forms, the #Page directive AutoEventWireup property on the markup code behind is defaulted to true, as opposed to false for VB. To see the #Page directive and all of its associated properties, right click on your web page in Solution Explorer and choose 'View Markup'
With AutoEventWireup=true, the runtime will automatically connect the event handlers it finds in your code that match the naming convention form of Page_EventName. You can however turn off this functionality and wire up the page event handlers manually using the standard C# += assignment. If you are using the AutoEventWireup=true, not only must your method name match, but obviously it must also have an appropriate method signature in order to be wired up automatically by the runtime.
See this KB for a good discussion of AutoEventWireup: http://support.microsoft.com/kb/324151
With respect to your second question, in C# there is no way to generate "stubs" for page events like there is in VB. As other have noted, including yourself -- there is similar functionality in C# for generating control object event stubs, via the property window. However, for page events you must know the event name and appropriate signature and code it yourself.
Where does C# define the hooking up of the event to the handler?
Page_Load is a special event that is automatically hooked up. It's a reserved name. So there's nothing you need to do for this event to be hooked up. Just declare it in the code behind.
namespace MyNamespace
{
public class Myclass : System.Web.UI.Page
{
override protected void OnInit(EventArgs e)
{
this.Load += new System.EventHandler(this.Page_Load);
}
private void Page_Load(object sender, EventArgs e)
{
}
}
}
Reference: https://support.microsoft.com/en-us/help/324151/how-to-use-the-autoeventwireup-attribute-in-an-asp-net-web-form-by-usi
Hello
I have read that events can be raised the same way as methods. Well it works for my custom events (I create a delegate, the event and I am able to raise the event by calling it).
However I am not able to manually raise events like MouseClick and other, it keeps saying that it must appear on the left side of the += operator. What is the problem?
While I am certain you'll get other answers more informative than this one, basically you can't "raise" an event outside the class that contains it. MSDN has this to say about events
Events are a special kind of multicast
delegate that can only be invoked from
within the class or struct where they
are declared (the publisher class). If
other classes or structs subscribe to
the event, their event handler methods
will be called when the publisher
class raises the event.
If you wanted to literally raise the event for, say, a Windows Forms Control MouseClick, you'd have to create a subclass of that control and either invoke base.OnMouseClick() or override it.
If this is a button, you can programmatically click it using the PerformClick method.
Sadly, this only works on buttons and not other types of Controls... except MenuItem.
If you want to click button you should call:
button1.PerformClick();
If you want to call MouseClick please refer to this forum, there is solution in c# using windows api:
private void button1_Click(object sender, EventArgs e)
{
//Enter your code here
}
void Page_Load(object sender, EventArgs e){
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button1_Click(this, e);
}
Let's say you want to manually raise the event "click". This works for me:
public partial class CustomButton : UserControl
{
public new event EventHandler Click;
private void lblText_Click(object sender, EventArgs e)
{
Click(this, e);
}
}
How to raise the SelectedIndexChanged event of an asp.net List control in a codebehind using C#?
If you're asking how to manually fire the event so that it can run whatever logic is attached: don't.
Your event handlers should be slim. If you need to perform the same operation from multiple places, then extract that functionality into its own method and have the event handler invoke that. For example:
private void CountryListBox_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateStates(ListBox1.SelectedItem.Text);
}
private void UpdateStates(string country)
{
StateListBox.DataSource = GetStates(country);
StateListBox.DataBind();
}
Now instead of trying to fire the SelectedIndexChanged event, you just invoke the method that this event handler refers to, i.e.
private void Page_Load(object sender, EventArgs e)
{
UpdateStates("USA");
}
Don't put complex logic in event handlers and try to raise those events from unexpected places. Instead, put the complex logic in its own method, so that you can perform the associated actions from elsewhere.
It is raised automatically.
Go in the Events section, lightening
bolt in properties window
alt text http://img704.imageshack.us/img704/6100/listbox.jpg
double click the place holder next to
event. This is what you will get.
protected void ListBox1_SelectedIndexChanged(object
sender, EventArgs e)
{
}
if you want to raise this event from another code block then, call
ListBox1_SelectedIndexChanged(sender,
e);
If what you want is more than just executing the code behaviour coded for the selected index (like listed in the previous answer), the short answer is there is no easy way. You can write a simple code that on prerender or render to explicitly define the control id variable in your rendered HTML and then use javascript to set the selected index. This will cause the postback that trigger the event. Alternatively you can register an ajax call back method and have the client calls that either when some event happened or by automatic timer.