简体   繁体   中英

How to generate events automatically for buttons without creating manually from properties if there are 'n' number of buttons?

IDE: Visual Studio 2010 Language: c# .net

I am generating events for buttons manually from properties. But, its becoming very lengthy process if there are suppose 20 buttons doing the same task like 'Mouse Hover' and 'Mouse Leave' . So, is there a way to copy events for all the other buttons ?

You can subscribe all your buttons to same event handler:

foreach(var button in Controls.OfType<Button>())
{
   button.MouseHover += Button_MouseHover; // add handler
   button.MouseLeave += Button_MouseLeave;
}

In that handler you can determine which exact button raised even by casting event source to button type:

private void Button_MouseHover(object sender, EventArgs e)
{
    var button = (Button)sender; // sender is one of buttons
    // use button.Name
}

Code above subscribes to events of all buttons. But if you want to filter them (eg by name) you can add filtering:

Controls.OfType<Button>().Where(b => b.Name.StartsWith("foo"))

Buttons can all share the same event, there's no need to have a seperate event for each button if they're doing similar tasks. (The object sender parameter will give you the Control which was clicked.

IF you select all the buttons (by keeping the ctrl key pressed) in the designer, you can then easily assign 1 event to all 20 buttons

In life you will not find shortcuts for everything,
In short there is no shortcut, but yes as mentioned in other post if you have same event handler and same action to be taken then this will help you reduce your work.

You don't have to do this manually, you can add event handlers from code as well. Also, if the logic is quite similar for all the buttons then you can use single event handler for all of them. Every event handler has sender property what will be set to the button that caused event.

Simple example would be something like this:

//at first assign event handlers
button1.Click += new EventHandler(Button_Click);
button2.Click += new EventHandler(Button_Click);


//single event handler
private void Button_Click(object sender, System.EventArgs e) 
{
    // Add event handler code here.
    Debug.WriteLine("You clicked: {0}", sender);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM