Custom controls

S

Sweetiecakes

Hey

I've Googled around a bit, but I just can't find an answer to this
simple question. Let's say that I have a button in a custom control. How
would I make an event when it's clicked, and make this event usable in a
form the custom control is in?

Thanks
 
P

Pavel Minaev

I've Googled around a bit, but I just can't find an answer to this
simple question. Let's say that I have a button in a custom control. How
would I make an event when it's clicked, and make this event usable in a
form the custom control is in?

You'll need to wrap the event in your own event with the same
signature. Something like this:

class MyControl : UserControl
{
private Button button;
public event EventHandler Click;

public MyControl()
{
button = new Button();
button.Click += button_Click;
Controls.Add(button);
}

private void button_Click()
{
OnClick(EventArgs.Empty);
}

protected virtual void OnClick(EventArgs e)
{
if (Click != null) Click(this, e);
}
}
 
I

Ignacio Machin ( .NET/ C# MVP )

Hey

I've Googled around a bit, but I just can't find an answer to this
simple question. Let's say that I have a button in a custom control. How
would I make an event when it's clicked, and make this event usable in a
form the custom control is in?

Thanks

It's very simple
class MyControl{
Button b;
public event EventHandler ButtonClicked;

OnInit{
b.Click += onButtonClick;

}
void onButtonClick{
if ( ButtonClicked!= null )
ButtonClicked( ....
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top