How to add an event handler for events from a button in C # from a source view (aspx)

What is the easiest way to create event handlers using webforms, for example, buttons from the original HTML view?

In VB.NET, it’s pretty easy to switch to code by page and use the combined fields of objects and events at the top to select and create.

In C # they are missing (and I really don't like the design).

+7
source share
2 answers

I agree that this is less trivial with C # and then with VB. My personal preference is to simply add a function with the following signature (always works):

protected void MyButtonName_Clicked(object sender, EventArgs e) { Button btn = (Button) sender; // remember, never null, and cast always works ... etc } 

Then, inside the code view of the HTML / ASP.NET part (the so-called declarative code), you simply add:

 <asp:Button runat="server" OnClick="MyButtonName_Clicked" /> 

I find it faster in practice, and then look through several property menus that do not always work depending on focus and successful compilation, etc. You can configure EventArgs for everything there is for this event, but all events work with the basic signature above. If you don’t know the type, just place a breakpoint on this line and hover over the object e when it breaks to find out the actual type (but most of the time you will know it beforehand).

After several times, it becomes second nature. If you do not like it, wait a minute for VS2010, it has become much easier.

Note. Both VB and C # never show objects or events of elements that are placed inside naming containers (i.e. GridView, ListView). In these cases, you should do it this way.

+2
source share
  • Make sure the Properties window is open.
  • Click anywhere in the item in the original view.
  • Click the lightning (event) icon in the Properties window.
  • Find the event for which you want to create a handler.
  • Double click on it.
+6
source share

All Articles