How to clone Control event handlers at run time?
I want to duplicate a control like a Button, TextBox, etc.
But I do开发者_StackOverflown't know how I can copy event handler methods (like Click
) to the new control.
I have the following code now:
var btn2 = new Button();
btn2.Text = btn1.Text;
btn2.size = btn1.size;
// ...
btn2.Click ??? btn1.Click
Is there any other way to duplicate a control?
To clone all events of any WinForms control:
var eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance);
var eventHandlerList = eventsField.GetValue(button1);
eventsField.SetValue(button2, eventHandlerList);
You just need to add the event handler method for the new button control. C# uses the +=
operator to do this. So you could simply write:
btn2.Click += btn1_Click
Alternatively, a somewhat more powerful approach is to use reflection. Of particular use here would be the EventInfo.AddEventHandler
method.
If you're simply looking to duplicate the HTML element that will eventually render (including attached event handlers), you can use below extension method to output a copy of the HTML.
/// <summary>
/// Render Control to HTML as string
/// </summary>
public static string Render(this System.Web.UI.Control control)
{
var sb = new StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
control.RenderControl(htmlWriter);
return sb.ToString();
}
Then you can use it to out put a copy in the aspx markup like this:
<%= btn1.Render() %>
If you want to modify, say, the text on the copy, you could do a string Replace on the Rendered html, or you could set the Text on the original button, and reset it after the Render
call in the asx, i.e.:
<% btn1.Text = "Text for original button"; %>
I didn't understand you question correctly. You can attach one event to multiple controls like this.
Button1.Click += button_click;
Button2.Click += button_click;
the better approach is using a component class and inherit the control to that Class
public class DuplicateButton : OrginalButton
{
}
you can make changes in the partial class so there is no need for creating events
精彩评论