79301530

Date: 2024-12-22 18:55:17
Score: 0.5
Natty:
Report link

after @Jeremy Dalmer helped me to overcome the problem with the static event handler and clarified in which class the event, delegate and eventHandler had to go, it was only a small step to follow @Flydog57's advice to use the standard event signature (object sender EventArgs e). For sake of simplicity I put the definition of the event argument class into the same file as the form. I think it is clear now, how to put even more data load on it. Finally it is possible to define the value variable as private in the user control. The result corresponds now to my current level of programming skills. It may be helpful for other newbies like me who search for basic examples for event handling using Winforms.

Full code for the form and the event argument:

using System;
using System.Windows.Forms;

namespace Events
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            this.myUserControl.Value_Change += this.Form1_ListenToChanges;
        }

        // EventHandler
        public void Form1_ListenToChanges(MyUserControl sender, ListenToChangesEventArgs e)
        {             
            //The following will work now:
            label1.Text = e.Count.ToString();
        }
    }

    public class ListenToChangesEventArgs : EventArgs
    {
        private int _Count;
        public int Count
        {
            get { return _Count; }
        }
        public ListenToChangesEventArgs(int count)
        {
            _Count = count;
        }
    }
}

Full code for the user control:

using System;
using System.Windows.Forms;

namespace Events
{
    public partial class MyUserControl : UserControl
    {
        private int value;

        // Delegate
        public delegate void MyUserControlEventHandler(MyUserControl sender, ListenToChangesEventArgs e);

        // Event
        public event MyUserControlEventHandler Value_Change;

        public MyUserControl()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            value++;
            // Raise event
            if (Value_Change != null) Value_Change(this, new ListenToChangesEventArgs(value));
        }
    }
} 
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Jeremy
  • User mentioned (0): @Flydog57's
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: oelgoetz