How to Copy Events?
- Hello,
I have a serie of buttons which I want to Copy during Runtime.
Some buttons have Click Events, some have MouseOver, MouseEnter etc.... all different events. How can I make an exact copy of my original button ?
Regards,
Andy.
Answers
Hi,
Use this code
Code Blockprivate
void button1_Click(object sender, EventArgs e){
TextBox t = (TextBox)CloneObject(textBox1);
t.Location = new System.Drawing.Point(64, 74);
this.Controls.Add(t);
this.ResumeLayout(false);
this.PerformLayout();
}
private object CloneObject(object o)
{
Type t = o.GetType();
PropertyInfo[] properties = t.GetProperties();
Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
foreach (PropertyInfo pi in properties)
{
if (pi.CanWrite)
{
pi.SetValue(p, pi.GetValue(o, null), null);
}
}
return p;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("Chenged");
}
Code : http://www.thescripts.com/forum/thread606031.html
HTH,
Suprotim Agarwal-----
http://www.dotnetcurry.com
-----
All Replies
Hi Andy,
I think it is not possible to copy the events. The best way is to subscribe the copied control event with the same function during runtime.
[code]
original.MouseEnter += new System.EventHandler(button_MouseEnter);
copied.MouseEnter += new System.EventHandler(button_MouseEnter);
void button_MouseEnter(...)
{}
[/code]
Robert-Paul
Hi,
Use this code
Code Blockprivate
void button1_Click(object sender, EventArgs e){
TextBox t = (TextBox)CloneObject(textBox1);
t.Location = new System.Drawing.Point(64, 74);
this.Controls.Add(t);
this.ResumeLayout(false);
this.PerformLayout();
}
private object CloneObject(object o)
{
Type t = o.GetType();
PropertyInfo[] properties = t.GetProperties();
Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
foreach (PropertyInfo pi in properties)
{
if (pi.CanWrite)
{
pi.SetValue(p, pi.GetValue(o, null), null);
}
}
return p;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
MessageBox.Show("Chenged");
}
Code : http://www.thescripts.com/forum/thread606031.html
HTH,
Suprotim Agarwal-----
http://www.dotnetcurry.com
------ Hello,
Thanks for the replies!
The code works indeed, but from the moment you pick another control like Label , it stops working .
any idea's why a Button or Label can't be "copied" with this code?
Regards,
Andy

