How do I programmatically invoke an event? - c#

I am creating a C# Windows Mobile application that I need to programmatically invoke the click event on a Button.
I have looked at the Button class and do not see a way to do this.

You might consider changing your design: at least move the logic from button1_Click handler somewhere else so that you'll be able to invoke it from wherever you want.

You can do something like this:
private void button1_Click(object sender, EventArgs e)
{
OnButtonClick();
}
private void OnButtonClick()
{
}
Then you can call your OnButtonClick() wherever you need to.

Not exactly the answer you were probably looking for:::
You might just call the code you want to run, move the meat of the code outside the OnClick handling method. The OnClick method could fire that method the same as your code.

The Control class, from which Button inherits, has the OnClick method, which invokes the Click event. Using reflection, you can call this method, even though it is declared protected. For instance, I created the following extension method:
public static void PerformClick(this Control value)
{
if (value == null)
throw new ArgumentNullException();
var methodInfo = value.GetType().GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(value, new object[] { EventArgs.Empty });
}
Although, this may be regarded as a dirty hack...

Anything that prevents you from simply invoking the method that handles the onClick event?

You can call the added event handler function as:
someControl_EventOccured(someControl, new EventArgs());
This works when the control's event argument e is not used inside the handler function, and mostly it's not used.

Related

Calling a method in a UserControl from another UserControl

I've been researching this problem for some time now and I cannot seem to find a solution that works. I want to call a method a UserControl from a method in another UserControl.
In UserControl1 I have a method:
public void update(int lineNum, double price)
{
// do stuff...
// then call the method in another UserControl
UserControl2 uc2 = new UserControl2();
uc2.refreshList();
}
And in UserControl2, I have a method:
public void refreshList()
{
// do stuff....
}
Of course, I have tried other methods of doing this other than simply creating an object of the UserControl and calling the method that way but nothing seems to work.
Having such dependencies between user controls is not good: it limits the use and makes them hardly testable in isolation.
You have several options to achieve what you want.
Let the caller do the orchestration
You did not state where the code resides that calls update. But since the method is public, I assume that this is called from outside UserControl1. Maybe it is possible to put the userControl2.refreshList() call there just after the call to userControl1.update()
Use an event
You could define an event in UserControl1 e.g. public event EventHandler UpdatePerformed and raise it at the end of the update method. Then in your form, subscribe to this event and call refreshList from there:
userControl1.UpdatePerformed += (s, e) => userControl2.refreshList();

Need to create an event handler that can remove itself when the event occurs

I'm not really sure how to do this, as I've never had a need for this pattern just yet. I'm looking for the correct pattern on creating an event handler in a separate class that can remove itself when the object that contains the event executes.
Basically, I want to create an EventHandler that occurs on the WPF Window.Close event. And, during the execution of the handler it removes itself from the Window.Close event. I hope that's specific enough to go on.
Also, is there a specific name for this pattern?
Try to do something like next:
RoutedEventHandler handlerLoad = null;
handlerLoad = delegate
{
//Do something
Window.Close -= handlerLoad;
};
Window.Close += handlerLoad;
would something like the following work?
public void EventHandlerSubscription_Invoked(object sender, EventArgs args)
{
_objectContainingEvent.MyEventHandler -= EventHandlerSubscription;
}
Sorry if this isn't sensible, I'm typing off the top of my head.
Please tell more about the 'what' of your project : what do you intend to do.
Maybe you would be interested in manual reset event, that triggers only
once unless you reset them :
http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx

Execute method On-Load of an object on a form in C#

E.g. instead of having a button to initiate the method, the method automatically happens without any user interaction - automatically.
private void button13_Click(object sender, EventArgs e)
{
try
{
ServiceController sc = new ServiceController();
sc.ServiceName = "Spooler";
if (sc.Status.ToString().ToLower() == "stopped")
{
serviceStatusLabel.Text = "Installed but stopped";
}
if (sc.Status.ToString().ToLower() == "running")
{
serviceStatusLabel.Text = "Installed and started";
}
}
catch
{
serviceStatusLabel.Text = "Service not installed";
}
}
I just want the Label object to show the service status when the form is loaded up, without using a button
EDIT: Given your comment, are you actually after the Form.Load event? It sounds like it. Any event handlers subscribed to that event will be executed "when the form is displayed for the first time".
(The confusing thing is that your title talks about "On-Load" of an object whereas it sounds like you really want the method to be called when the form is loaded.)
It's not really clear what you mean by "when its output on the form" but you might want to look at the TextChanged and VisibleChanged events. That's if you want something to happen when the label is altered.
If you're looking for when the service status is altered, it doesn't look like there's an event raised for that, I'm afraid. Note that it would be much cleaner to switch on the enum value rather than to convert it to a string, lower it, and then compare that with hard-coded constants.
... Do I get your question correctly?
You want a piece of code to be executed when an object or the form is loaded?
Well that's easy :p
Click on your object (or form) in the designer, in the properties dock, click the lightning bolt icon, go to the Load or Show event, and double-click the box.
A new piece of code should now be created in the code view, something like this:
private void Object_Load(blabla) handles Object.Load
{
}
Whatever code is in that event will be executed when the object is loaded or shown.
If you create a handler for the Load event, it will run when the form gets loaded.

how to pass command argument while calling link button onclick function dynamically? (c#)

I have a function for which i am sharing a group of link buttons with.
the function signature is like:
protected void FunctionName(object sender, EventArgs e)
{
...
}
Now I have about 4-5 link buttons which i am using to call the same function but just filtering the stuff via command argument like:
<asp:LinkButton ID="lbAll" runat="server" Text="All"
CommandArgument="all" OnClick="FunctionName"></asp:LinkButton>
<asp:LinkButton ID="lbTop" runat="server" Text="Top"
CommandArgument="top" OnClick="FunctionName"></asp:LinkButton>
(...)
Now, I have a drop down box which needs to do the same thing essentially (on just two of the selected values), i just need to call this function and pass the "all" or "top" argument to the Function: "FunctionName"
this is in C#
I tried to call that function like
FunctionName(this, New EventArgs());
but I dont know how to pass the Argument?
Any ideas on this?
Thanks!
Pass the LinkButton with the correct CommandArgument instead of the this:
FunctionName(lbAll, EventArgs.Empty)
But you really should use the OnCommand event instead of OnClick. OnCommand has CommandEventArgs as second parameter. So you can get them with e.CommandArgument in the method. And call the method width:
FunctionName(this, new CommandEventArgs("CommandName", "CommandArgument"));
Editing for clarity
Your event handler for the click event will have two parameters, a sender and an event args object. The sender is the object that triggered the event (the linkbutton). In that event handler you can cast the sender to the right object type and access its properties.
((LinkButton)Sender).CommandArgument
Using this method you don't need to explicitly pass your argument, you just retrieve it from the sender.
Alternatively (and probably better) you can use the "OnComand" event handler. Looking up the property you are already using at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.commandargument.aspx you will see that this event handler receives a CommandEventArgs parameter that has a property that exposes the CommandParameter object. eg:
void LinkButton_Command(Object sender, CommandEventArgs e)
{
Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}
(from that MSDN page).
OK. I think I missed my point on the last answer having realised its a question of calling the event handler from somewhere in code that isn't that event...
What I would suggest is that you refactor your event handler to take out the functionality and put it into a separate method or two. eg in pseudocode:
protected void FunctionName(object sender, EventArgs e)
{
if (top)
DoTop();
else if (all)
DoAll();
}
private void DoTop()
{
//do stuff
}
private void DoAll()
{
//Do different stuff
}
This should make it really easy then to just call the bit of code that you need. Althoguh I'm not sure I suspect its considered bad practice to call an event handler just because you need some of its functionality. Its certainly looking like more work than it needs to be. :)
You could of course instead have a method that takes a parameter and then deals with it appropriately (effectively factoring out everything in FunctionName).
I think this answers your question better. If not I'm just going to go home. ;-)

What is the proper way to fire an ASP.NET control event programatically?

What is the proper way to fire an ASP.NET control event programatically?
I am looking to refactor a little code and I see items sprinkled in the code behind coded like this; the developer is calling the event handler and saturating it with params.
for a DropDownList
ddlAddress.SelectedIndex = 1;
ddlAddress_SelectedIndexChanged(null, new EventArgs());
&
for a RadioButtonList
rblAction.SelectedIndex = 0;
rblActionType_SelectedIndexChanged(null, new EventArgs());
Is this normal coding practice? What should I do as to not disrupt/break the page?
Any thoughts or suggestions would be appreciated.
Thanks,
~ck in San Diego
I would start by removing all of the code from the actual event's method and refactor it into a new method called AddressChanged or whatever else fits your naming standards. You can then call that new function from anywhere else in your code.
protected void ddlAddress_SelectedIndexChanged(object sender, EventArgs e){
AddressChanged();
}
private void AddressChanged(){
//do the changed event
}
private void doingSomething(){
ddlAddress.SelectedIndex = 1;
AddressChanged();
}
Note that you're calling the event handler programatically, not the event.
This can be indicative of a design problem, because usually event handlers should not be relying on each other to execute in a specific order. However, I have seen this pattern and even used it occasionally when code that existed in one event handler needed to be executed in another event handler and could not be refactored at that time. You can set the "sender" to indicate that it's coming from elsewhere in the code and not from the expected control itself, but this is a little bit too opaque to be called a good design.
It would be better practice to refactor out the code that needed to be shared, and put it in a private method, and have both event handlers use it, passing in whatever data from the sender or the eventargs that it needed.

Categories