Your code is a pain to read. You should never use names like
UserControl1
,
button1
or
button2_Click
— they violate (good) Microsoft naming conventions. I know, they are auto-generated. Never use such names, they are supposed to be renamed to something semantic.
You do some other bad things. First of all, you should not expose
button1
, it breaks good encapsulation. Don't use
RemoveByKey
, and, generally, never assume certain values of the property
Name
. This property is for designer, not for your code.
First of all, expose the button properly, not as a control, but only as the event; you can expose some properties, separately:
class MyUserControl {
Button myButton = new Button();
internal MyUserControl() {
myButton.Click = += (sender, eventArgs) => {
if (MyButtonClick != null)
MyButtonClick.Invoke(this, new System.EventArgs());
};
}
internal System.EventHandler MyButtonClick;
internal string MyButtonName {
get { return myButton.Name; }
set { myButton.Name = value; }
}
}
Now, you can properly add the control instances:
Panel parent = new Panel();
MyUserControl first = new MyUserControl();
first.MyButtonClick += (sender, EventArgs) => {
MyUserControl second = new MyUserControl();
parent.Controls.Add(second);
};
first.Parent = parent;
Note that
anonymous methods for event handlers make the code much simpler and better isolated. Child controls of the user control are not exposed, only some minimal set of properties and events is exposed.
—SA