Q-bertsuit
Q-bertsuit

Reputation: 3437

Mouse click event not fireing

I have created a User Control that contains a button. The goal is to create a custom layout for my buttons that will be reused through the application:

public partial class Button : UserControl
{
    public Button()
    {
        InitializeComponent();
        button1.BackColor = Color.FromArgb(0, 135, 190);
        button1.ForeColor = Color.Black;
    }

    [Description("Test text displayed in the textbox"), Category("Data")]
    public string TextSet
    {
        set { button1.Text = value; }
        get { return button1.Text; }
    }
}

When I add the Button user control to my application and create an event for MouseClick, the event does not fire. (Obviously each instance of the button will have a different event for mouse click)

Do I have to do something in my Button User Control code to forward the mouse click event?

Upvotes: 1

Views: 103

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

You are subscribing to clicks of user control. But you are clicking a button which is located on your user control. Thus click event of user control is not fired. You can raise user control's click event manually when button1 is clicked:

public partial class Button : UserControl
{
    public Button()
    {
        // note that you can use designer to set button1 look and subscribe to events
        InitializeComponent(); 
        button1.BackColor = Color.FromArgb(0, 135, 190);
        button1.ForeColor = Color.Black;
    }

    // don't forget to subscribe button event to this handler
    private void button1_MouseClick(object sender, MouseEventArgs e)
    {
        OnMouseClick(e); // raise control's event
    }

    // ...
}

But it's better to inherit your button from Button class directly:

public partial class CustomButton : Button
{
    public CustomButton()
    {
        BackColor = Color.FromArgb(0, 135, 190);
        ForeColor = Color.Black;
    }

    [Description("Test text displayed in the textbox"), Category("Data")]
    public string TextSet
    {
        set { Text = value; }
        get { return Text; }
    }
}

Upvotes: 2

Related Questions