Custom controls

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sweetiecakes

    Custom controls

    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
  • Pavel Minaev

    #2
    Re: Custom controls

    On Aug 5, 3:25 pm, Sweetiecakes <tyhm...@gmail. comwrote:
    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(bu tton);
    }

    private void button_Click()
    {
    OnClick(EventAr gs.Empty);
    }

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

    Comment

    • Ignacio Machin ( .NET/ C# MVP )

      #3
      Re: Custom controls

      On Aug 5, 7:25 am, Sweetiecakes <tyhm...@gmail. comwrote:
      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( ....
      }
      }

      Comment

      Working...