V
V
VavilonBase2021-02-04 15:44:31
C++ / C#
VavilonBase, 2021-02-04 15:44:31

WinForms how to make an event handler that refers to a generic method?

Hello. The question is as follows, there is such a generalized method:

private void ClickOnReferences<T>(object sender, EventArgs e)
            where T: Form, new()

        {
            string name = ((ToolStripMenuItem)sender).Name;
            if (!CheckMdiChildrenInMdiContainer(name))
            {
                var form = new T();
                form.MdiParent = this;
                form.Name = name;
                form.Show();
            }
        }


It is necessary to subscribe to it several event handlers on click
. I did this
this.Students.Click += new System.EventHandler(this.ClickOnReferences<StudentsForm>);

If you run the assembly, then after saving it will look like this
this.Students.Click += new System.EventHandler(this.ClickOnReferences);

And it starts to give an error that you need to explicitly define the type of the argument.
Maybe I'm doing something wrong? I have the following essence of the task, when you click on a certain ToolStripMenuItem, you need to open a certain form, at first I made my own handler for each item and everything worked, but I decided to make it generalized and came across such a feature. Also, if you run the application instead of assembling, then everything will work fine, but then the situation repeats

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2021-02-04
@VavilonBase

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Click += new EventHandler(button1_Click<List<object>>);
            button2.Click += new EventHandler(button1_Click<object>);
        }

        private void button1_Click<T>(object sender, EventArgs e) where T: new()
        {
            var o = new T();
            MessageBox.Show(o.GetType().FullName);
        }
    }

Here I sketched a similar one, nothing disappears, the WinForms project. Launched, cohabited, cleaned, rebuilt the project, everything is in place. VS19. Install the latest studio or all updates to it.
PS: Of course, such a solution is not bad (Although WPF is much more elegant, without any manual assignment of events).
Option 2. if the glitch remains
public partial class Form1 : Form
    {
        private Dictionary<string, Type> _forms = new Dictionary<string, Type>();
        public Form1()
        {
            InitializeComponent();
            _forms.Add("button1", typeof(Form));
            _forms.Add("button2", typeof(Form));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var name = (sender as Button).Name;
            Form form = (Form)Activator.CreateInstance(_forms[name]);
            form.Show();
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question