I was doing some research on my project (ASP.NET Web Forms) and came across 2 event types that seem similar, OnCommand and OnClick. I have read through the MSDN pages but I am still unclear on the differences between them.
What is the difference between OnCommand vs OnClick and when would I want to use which event?
//edited to specify for type of app
If you find the documentation a bit unclear, that's understandable.
What happens is that OnClick is a lower-level event than OnCommand. You can think of OnClick as being more like a physical event, and OnCommand as being more like a logical event, so to speak.
When the control is clicked, it receives an OnClick event which tells the control that there has been a click. The control may do various things as a response. If the control is associated with a command, and if default processing of the event is allowed to take place, then the system will follow this with an OnCommand event.
(I am not sure / don't remember how much control you have over the suppression of default processing in WinForms, but you can certainly control that in the underlying Win32 programming layer.)
The OnCommand event may be triggered by means other than a click. For example, you may use a keyboard shortcut to activate a control, in which case there will be no OnClick.
The knowledge to take home from all this is the following:
Never use OnClick when OnCommand will suffice.
If you write your program to use OnClick for triggering Business Logic operations, then your program will require the user to use the mouse. There are many users who cannot use the mouse due to disability, there are many users who simply prefer the keyboard over the mouse, and there are many devices that do not even have a mouse.
(On those devices a click will often be simulated by a touch, but that's not guaranteed, and in any case all these clunky simulations should have never been necessary in the first place, the only reason they are added is because programmers were careless in the first place and they were doing silly things like triggering actions on OnClick instead of OnCommand.)
It would be okay to use OnClick if you were writing your own control. For example, if you were writing your own edit box control, and you wanted the user to be able to click somewhere within the control in order to place the caret at that exact location, then it would be okay to do that as a response to the OnClick event being triggered. But note how this action is for internal use of the control only, it does not trigger any action which is external to the control.
This is straight from the msdn page https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.oncommand.aspx
But trying to explain with little verbosity:
OnCommand is used to pass extra arguments to the handler. For example, if you have two buttons to sort list ascending and descending. Instead of writing separate OnClick handlers for each button , you can define single handler for both buttons and pass CommandName and CommandArgument
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
switch(e.CommandName)
{
case "Sort":
// Call the method to sort the list.
Sort_List((String)e.CommandArgument);
break;
}
}
so here you have single handler where you can handle multiple buttons' clicks depending on what command argument buttons are passing.
Within the MSDN documentation it states in the remarks section the key difference.
With OnCommand:
The Command event is raised when the Button control is clicked. This event is commonly used when a command name, such as Sort, is associated with the Button control. This allows you to create multiple Button controls on a Web page and programmatically determine which Button control is clicked.
With OnClick:
The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control (for instance, with a Submit button).
So, if you just want some code to execute when a button is clicked, but don't care about specific execution for specific cases then OnClick is just fine.
Edited to add: With OnCommand you could potentially have one handler that handles events from multiple buttons and executes the proper code based on the command name that's passed.
Related
I'm working in C# and I need a button to become instantly disabled when a user clicks it. However, if I put as the very first line in the OnClick function
MyButton.Enabled = false;
it does nothing. The button remains enabled until it hits some sort of stop, whether it be the Catch block or the end of the function.
I was thinking that in VB/VBA you can use DoEvents() and that allows the code to catch up to itself. However, in C# there doesn't appear to be a DoEvents method.
This is a little different than the linked question, in that my OnClick code looks like:
OnClick="btnSubmit_Click"
and that user's OnClick code looks like:
onClick="this.disabled=true;
this.value='Sending…';
this.form.submit();"
When I tried to change my code to:
OnClick="this.disabled=true; btnSubmit_Click"
I got an error.
Compiler Error Message: CS1041: Identifier expected; 'this' is a
keyword
How can I do this in a C#/asp.net environment?
OnClick is a server-side event of the Button. So you cannot write:
OnClick="this.disabled=true; btnSubmit_Click"
OnClick accepts only the method-name of the server-side event handler.
If you want to handle the client-side button-click event to prevent that the user can click on it multiple times use OnCLientClick:
OnCLientClick = "this.disabled=true;"
You also have to set UseSubmitBehaviour to false.
Read: Disable a button control during postback.
You will need to utilize client-side JavaScript. One way is to utilize the OnClientClick property of your asp.net button control.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick(v=vs.110).aspx
This is server-side and will be executed on PageLoad/Postback -
MyButton.Enabled = false;
I have few buttons in my windows application which has mnemonics.Now if i press multiple keys the events of the button clicks gets fired as i have used mnemonics.
But the behaviour is not as expected,because second button event handler is getting executed before the first button event handler has finished its execution,and also i have written my code in such a way that in the event handler of first button i am disabling my second button,still the second button event handler is getting executed.The problem here is due to mnemonics.PLease suggest me a better way to handle mnemonics as soon as possible.
Thanks in advance.
If your logic is tied to your buttons, change that. Let your buttons merely manipulations an object that implements your logic. You can then check in this object whether the requested action is allowed (i.e. whether the previous operation has finished.
Alternatively you can just disable buttons when running and re-enable then when.finished.
Let's say we have a pretty standard form with a textbox and a button (for simplicity). You want to handle a Click event and do some stuff based on user's input.
I was wondering, does it matter, when exactly you wire up an event handler for the Click event in a code-behind? If it does, where is the best place to put it? Page load? Page init? I've tried both places, but didn't notice any difference. Or it's just a personal preference of the programmer? I've already searched the internet couple of times, but haven't found any satisfactory answer.
I know when the actual method execute, just not sure about the wiring-up part.
As you know, there are several Page_xxx event handlers, like Init, Load, Prerender... This events exist in Controls, and Pages as well as User controls (in fact they're derived form Control, which holds all these events).
This events are related to the ASP.NET Page Life Cycle
If you read the page pointed to by this link carefully you will understand when the events are triggered. So, if you bind your event handler in any page lifecycle event that happens before the events are triggered, it's guaranteed that your event handlers will be bound in time to be triggered.
These are the main lifecycle steps:
PreInit -> Init -> InitComplete -> PreLoad -> Load -> [Control events] ->
LoadComplete -> PreRender -> SaveStateComplete -> Render -> Unload
Not all of them have associated events, but, if it's necessary you can override the corresponding OnXxx() function, like OnPreInit(). (This is usually only done on custom server controls).
You can bind events in Page_Init or Page_Load, because the control events are triggerd after the loading of all the controls has finished. The Load step happens in top-bottom way, first in the Page, and then recursively in all the children controls.
After Load finishes, the first events which are triggered are the Change Events, like TextChanged or SelectionChanged. Then are triggered all the other events, like Click.
If you bound the events in PreRender or Unload, they wouldn't be triggered. If you did in Init or Load, they would.
So it could look like it's safe to bind in Init or Load, but that's not true:
It could look like there's no special reason to bind them on Init or Load, because they'll be triggered later in the page life cycle. But, as the binding defined in the .aspx happens during Init, a programmer will expect that all events are already bound in the Load event. What would happen if this programmer raised an event of a child control in code behind? The Load event happens first in the root of the control tree, and them on all of the children, recursively. So, by the time the programmer is trying to raise the event of the child control, it won't be already bound. So this won't work as expected. This is more than enough to consider unsafe to bind events in Load event. That's why you should always bind events in Init.
Look at this diagram to see the order of execution of Page & children events:
ASP.NET Page Life Cycle Diagram
I have been wiring mine up in the control tag. If I do it this way it is clear that an event handler is present.
<asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
If I had to wire up an event handler in the codebehind, I would put it in Page_Load as a private function call.
What I have is a popup defined within a user control, that is opened within a taskbar user control, which is attached to a master page, such that:
MasterPage.TaskBarUC.PopupUC
Within the popup, there are two buttons, one to save what the user is trying to do within a database, and one to cancel. I have some codebehind that does the work when the user clicks either button.
So every page has the taskbar, and they can click a button on the taskbar to access the popup and save the information. It works perfectly. However, there is one specific page within the site that needs to access the same popup from a button located on the page, as well as from the taskbar.
The button works, and it opens the popup, but for some reason, and only in this case, the "Save" button doesn't activate my codebehind. It DOES perform the validation that I have it do though. What is also weird is that the cancel button, which also activates some codebehind, does do what its supposed to.
I tried putting a breakpoint right at the beginning of my "Save" event handler, and it never reaches it. Its as if the button is only validating, and completely ignoring its OnClick event.
.aspx
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"
ValidationGroup="Validation" />
I guess what happens is that the validation process has failed, which cancel the handling of the Button.Click event.
To check this possibility try to set the value of the Button.CausesValidation property to false and see if the Button.Click handling is going to continue or not.
Button.CausesValidation property to false worked for me. I am using required field validator for different button. I think this could stop post back even for all other button click events (serverside).
I am developing a web application in asp.net and c#, now in a particular aspx page whenever I doubleClick(design view) on a button or on a drop down list, instead of going to
public void btn_click event or DropDown_SelectedIndexChanged event, the cursor points to protected void Page_Load only. Strange!! any remedy?
Not a fix for your VS misbehaving, if it is doing so. But this will help you wire up your events and perhaps notice anomalous event assignments:
Select the control in question, right-click>Properties, switch to the 'events' tab (lightning bolt) and either enter the name of a method or simply double click the empty space to generate an event handler in your codebehind.
This is also where you will see if Page_Load is already, for whatever reason, assigned to the event you are having trouble with.
HTH
May be both your btn_click event and DropDown_SelectedIndexChanged event delegates have Page_Load as the method. Check your events tab for button and dropdown.
this happens to me when I have my project running in debug mode and forget to stop it before editing my code. Long shot, but sometimes the obvious things are the things we overlook :)