Add events to custom user controls

Hemanth B 886 Reputation points
2022-02-10T10:42:30.43+00:00

Hi, I created a custom checkbox with picture boxes as a UserControl. Now how do I add the CheckedChanged event to it? I also created a tab control, how do I add SelectedTabChanged event to it?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,190 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,026 Reputation points
    2022-02-10T11:53:49+00:00

    Create an event, for example checked changed on a CheckBox.

    public partial class UserControl1 : UserControl
    {
        public delegate void OnCheckChanged(CheckBox sender);
        public event OnCheckChanged OnCheckChangedEvent;
        public UserControl1()
        {
            InitializeComponent();
        }
    
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            OnCheckChangedEvent?.Invoke((CheckBox)sender);
        }
    }
    

    Subscribe in the form to the event above

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            DemoControl.OnCheckChangedEvent += DemoControlCheckChanged;
        }
    
        private void DemoControlCheckChanged(CheckBox sender)
        {
            MessageBox.Show($"{sender.Checked}");
        }
    }
    

    Or change the Modifiers property of the control, in this case a CheckBox from private to public than directly subscribe to the event. This is not recommended, always scope to the smallest needs possible.

    0 comments No comments

0 additional answers

Sort by: Most helpful