bunNyBug
bunNyBug

Reputation: 146

In which code file and where exactly in the file should I assign event handlers to controls?

Exactly where I must write this code?

button1.MouseHover += Common_MouseHover;

The problem is I want to declare one event handler and point each button at it. This is the common handler:

private void Common_MouseHover(object sender, EventArgs e)
{
     Button btn = sender as Button;
     if (btn != null)
         btn.Image = pic
}

But I dont know where i must write:

button1.MouseHover += Common_MouseHover;
utton2.MouseHover += Common_MouseHover;
.. etc

In designer? Where exactly?

Upvotes: 0

Views: 94

Answers (3)

Mark Hall
Mark Hall

Reputation: 54532

Either in the designer or the Constructor of your Form or if you are creating dynamic Buttons at the time of creation.

public Form1()
{
    InitializeComponent();

    button1.MouseHover += new EventHandler(Common_MouseHover);
    button2.MouseHover += new EventHandler(Common_MouseHover);

}

If in the Property Editor.

enter image description here

Upvotes: 3

Prateek Singh
Prateek Singh

Reputation: 863

Call following function in your form Constructor after InitializeComponent(); -

    private void init()
    {
        foreach (Control ctrl in this.Controls)
        {
            if (ctrl is Button)
            {
                (ctrl as Button).MouseHover += new EventHandler(Common_MouseHover);
            }
        }
    }

Call it like this -

    // Form Constructor
    public Form3()
    {
        InitializeComponent();
        Init();
    }

Upvotes: 0

MrShoes
MrShoes

Reputation: 485

Technically, it depends when you want to assign it. For example, you might not want the event to be handled by that method until certain conditions are met: then you assign the event handler once the conditions are true.

Bear in mind that assigning event handlers can cause memory leaks if you aren't careful. For example, you might have a timer that continually assigns the same event handler to the event. You need to check if the event already has the event handler, or if it's null, or whatever you need to prevent duplication. You might also want to remove event handlers dynamically using the -= operator.

For the example given, the form's constructor seems right, and is the most common place for assigning event handlers manually.

Upvotes: 0

Related Questions