Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

What is the easiest way to create code-behind (webforms) event handlers for say a button from HTML source view?

In VB.NET it is quite easy to switch to code behind page and use the object and events combo boxes along the top to select and create.

In c# those are missing (and I really don't like design view).

like image 825
David Avatar asked Dec 20 '09 16:12

David


2 Answers

  • Make sure the Properties window is open.
  • Click anywhere in the element in source view.
  • Click the lightning symbol (events) in the Properties window.
  • Find the event you want to create a handler for.
  • Double click it.
like image 90
Mark Byers Avatar answered Oct 19 '22 23:10

Mark Byers


I agree that this is less trivial with C# 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 (aka the declarative code) you simply add:

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

I find this faster in practice then going through the several properties menus, which don't always work depending on focus and successful compile etc. You can adjust the EventArgs to whatever it is for that event, but all events work with the basic signature above. If you don't know the type, just place breakpoint on that line and hover over the e object when it breaks to find out the actual type (but most of the time you'll know it beforehand).

After a few times doing this, it becomes a second nature. If you don't like it, wait a moment for VS2010, it's been made much easier.

Note: both VB and C# never show the objects or events of elements that are placed inside naming containers (i.e., GridView, ListView). In those cases, you have to do it this way.

like image 37
Abel Avatar answered Oct 20 '22 00:10

Abel