Answer the question
In order to leave comments, you need to log in
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();
}
}
this.Students.Click += new System.EventHandler(this.ClickOnReferences<StudentsForm>);
this.Students.Click += new System.EventHandler(this.ClickOnReferences);
Answer the question
In order to leave comments, you need to log in
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);
}
}
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 questionAsk a Question
731 491 924 answers to any question