Search code examples
c#winformsbuttoncase

How can i foreach all buttons in winforms (C#)


Please can you help me? I have all buttons in winforms.designer.cs and I assign all buttons the same handler. The handler is MouseEnter and MouseLeave. I need to find all buttons and assign each a different MouseEnter and MouseLeave.

I tried this on a button, but it doesn't work.

private void createButton_MouseEnter(object sender, EventArgs e)
{
    createButton.Cursor = NativeMethods.LoadCustomCursor(Path.Combine(collection.source, collection.cursor_hand));
    switch (Name)
    {
        case "createButton":
            this.createButton.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.create_on));
            break;
    }
}

Solution

  • You can easily loop through your all buttons using OfType extension method like this:

    foreach(var button in this.Controls.OfType<Button>())
    {
        button.MouseEnter += createButton_MouseEnter;
        button.MouseLeave += createButton_MouseEnter;
    }
    

    And in your createButton_MouseEnter if you want to get current Button's Name you can do the following:

    private void createButton_MouseEnter(object sender, EventArgs e)
    {
       var currentButton = sender as Button;
       var name = currentButton.Name;
       ...
    }