views:

652

answers:

3

Is there a shortcut to add an event method for a control? If I have a button, I want to add the Click method without having to type it out or switch to design view.

EDIT: Seriously! When i did this in VB I had a drop down list of all the controls and their events. Is that so hard to do for C#?

+5  A: 

Winforms? Webforms? What?

One option is to (after initialization) hook the event your self - intellisense supplies the event name, and [Tab][Tab] creates the method stub - i.e.

public MyForm()
{
    InitializeComponent()
    someButton.Click += (press [tab][tab] now)
}

and it does the rest... likewise in web-forms at the appropriate place.

This gives you:

public MyForm()
{
    InitializeComponent();
    someButton.Click += new EventHandler(someButton_Click);
}

void someButton_Click(object sender, EventArgs e)
{
    throw new NotImplementedException(); // your code here ;-p
}
Marc Gravell
A: 
public partial class MyUserControl : System.Web.UI.UserControl
{

public delegate void ButtonClickEventHandler(object sender,EventArgs e);
public Event ButtonClickEventHandler Button_Click;

 protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (Button_Click!= null)
                Button_Click(sender,e);
        }
}

Default.aspx

protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            MyUserControl.Button_Click+= MyUserControl_Button_Click;
        }

 void MyUserControl_Button_Click(object sender,EventArgs e)
        { }
Barbaros Alp
+1  A: 

Have you looked into creating a snippet? Here is a snippet I use to create anonymous methods that hook up to an event.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
    <CodeSnippet Format="1.0.0">
     <Header>
      <Title>anonymous</Title>
      <Shortcut>__anonymous</Shortcut>
      <Description>Code snippet for an anonymous method</Description>
      <Author>Andrew</Author>
      <SnippetTypes>
       <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
     </Header>
     <Snippet>
      <Declarations>
       <Literal>
        <ID>event</ID>
        <Default>base.Init</Default>
        <ToolTip>Event to attach</ToolTip>
       </Literal>
       <Literal>
        <ID>args</ID>
        <Default>EventArgs</Default>
        <ToolTip>Event argument type</ToolTip>
       </Literal>
       <Literal>
        <ID>name</ID>
        <Default>args</Default>
        <ToolTip>Event arg instance name</ToolTip>
       </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[$event$ += delegate(Object sender, $args$ $name$) {
       $end$
      };]]>
      </Code>
     </Snippet>
    </CodeSnippet>
</CodeSnippets>

Also here is an article explaining how to create them and how they work.

Andrew Hare
it looks like a great thing, i ll try it as soon as possible.Thanks for the info
Barbaros Alp