That suggests to me that you are going about this in completely the wrong way. It sounds like you have created a form, added a
TabControl
to that, added a
Panel
to one of the
TabPages
and then, when adding new
TabPages
, you want to create duplicates of that
Panel
and its contents. That's wrong.
What you should is is start by creating a user control. You add a user control to your project in much the same way as you do a form, then you design it and add code in exactly the same way as you do a form. All the child controls that you're currently adding to your
Panel
, you would add to the user control instead.
When you build your project, your user control will be automatically added to the Toolbox and you can then use it exactly the same way as you would any other control, both in the designer and in code. That means that you would add an instance of the user control to your first
TabPage
in the designer and then, when you wanted to create new
TabPages
, you would simply add an instance of your user control to them in code. There's no need to worry about copying anything; you simply add one control to each
TabPage
.
If you wanted to take things a step further, you could even create your own custom
TabControl
and
TabPage
classes. The custom
TabPage
could add the user control instance to itself and the custom
TabControl
could provide a means to access instances of that custom
TabPage
.
Just note that you would likely need to add some pass-through functionality to your user control. By that I mean that it should provide members that enable indirect access to members of the child controls so that the form only needs to deal with the user control. For instance, let's say that you have a
TextBox
whose
Text
you need to get when a
Button
is clicked. In that case, the user control would handle the
Click
event of the
Button
and then raise its own event that the form could handle, as well as providing a property for the form to get and set that would then get and set the
Text
of the
TextBox
.
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string TextBox1Text
{
get => textBox1.Text;
set => textBox1.Text = value;
}
public event EventHandler Button1Click;
private void button1_Click(object sender, EventArgs e)
{
Button1Click?.Invoke(this, EventArgs.Empty);
}
}