Does C# have a Handles keyword?
Asked Answered
C

5

5
Protected Sub Menu1_MenuItemClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemClick


End Sub

In VB.net, we have the Handles keyword, I'm wondering if C# has anything comparable. Or do you have to manually wire all the methods to each control's event (in ASP.NET especially)?

Cum answered 25/5, 2011 at 20:56 Comment(0)
T
10

Nope. You will have to wire up the event like this

Menu1.MenuItemClick += Menu1_MenuItemClick;
Terpsichore answered 25/5, 2011 at 20:58 Comment(2)
So do you have to do this all in the Page_Load event or somewhere else? What's the best way to handle this in C#?Cum
@Cum for asp.net you can do it in the markup if that's possible ,like <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick"> if not you can do it from code in Page_Load or probably Page_InitTerpsichore
F
3

You have to assign the events yourself using the += syntax.

Fairbanks answered 25/5, 2011 at 20:58 Comment(0)
B
3

Its pretty easy to setup handlers in C#. In my option much easier than VB.Net. You'll need to make sure the handler gets setup early enough in the page to get fired off. Just type in the object name (Menu1) . (the name of the event) the "+=" and hit tab twice. Visual Stuido will generate everything for you.

Beverlee answered 25/5, 2011 at 21:3 Comment(1)
Nice, I didn't knew I could use 'tab twice' in that spotImpersonality
F
1

Generally this goes right in the markup.

<asp:Menu ID="Menu1" runat="server" onmenuitemclick="Menu1_MenuItemClick"></asp:Menu>

and in the codebehind it looks like

protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{

}

You can generate all of this in Visual Studio from the designer. Select the menu control, go to the properties window (f4), view the events list (the lightning bolt) and double click the event name.

You can also subscribe an event handler manually with += but you have to do it every time the page loads.

Forfeiture answered 25/5, 2011 at 21:5 Comment(0)
S
0

If you don't mind doing so, you can always set the AutoEventWireUp to "true". Then C# will automatically bind event handlers with "VB" names.

Sulla answered 1/8, 2011 at 21:22 Comment(2)
There is a performance penalty for this: msdn.microsoft.com/en-us/library/…Deduction
So, you comment on a 4.5 year old post, commenting a web techology that is soon to be replaced. OK. Yes, there is a penalty by doing this. But System.Web is a big performance hog in itself, that's why dotnet core is due in few weeks... :)Sulla

© 2022 - 2024 — McMap. All rights reserved.