So, I'm adding Panel
s by code to my flowLayoutPanel
:
Panel pnl = new Panel {Name = panelname}; //panelname is a name combined with a continous number
CopyControl(panel1,pnl, number);
pnl.Visible = true;
flowLayoutPanel1.Controls.Add(pnl);
(I already have a Panel
in that flowLayoutPanel
and I just copy its property's)
CopyControl:
private void CopyControl(Control sourceControl, Control targetControl, int number)
{
// make sure these are the same
if (sourceControl.GetType() != targetControl.GetType())
{
throw new Exception("Incorrect control types");
}
foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
{
object newValue = sourceProperty.GetValue(sourceControl, null);
MethodInfo mi = sourceProperty.GetSetMethod(true);
if (mi != null)
{
sourceProperty.SetValue(targetControl, newValue, null);
}
}
try
{
foreach (Control c in sourceControl.Controls)
{
if (c.GetType() == typeof(Button))
{
Button btn = new Button();
btn.Name = "button" + number;
btn.Click += CopyTextToClipboard;
//get same location
Button btnold = this.Controls.Find("button1", true).FirstOrDefault() as Button;
btn.Text = btnold.Text;
btn.Location = btnold.Location;
btn.Size = btnold.Size;
targetControl.Controls.Add(btn);
}
else if (c.GetType() == typeof(RichTextBox))
{
RichTextBox rtb = new RichTextBox();
rtb.Name = "richTextBox" + number;
RichTextBox rtbold = this.Controls.Find("richTextBox1", true).FirstOrDefault() as RichTextBox;
rtb.Location = rtbold.Location;
rtb.Size = rtbold.Size;
targetControl.Controls.Add(rtb);
}
else if (c.GetType() == typeof(Label))
{
Label lbl = new Label();
lbl.Name = "label" + number;
Label lblold = this.Controls.Find("label1", true).FirstOrDefault() as Label;
lbl.Text = lblold.Text;
lbl.Location = lblold.Location;
lbl.Size = lblold.Size;
targetControl.Controls.Add(lbl);
}
else if (c.GetType() == typeof(TextBox))
{
TextBox tbox = new TextBox();
tbox.Name = "textBox" + number;
TextBox tboxold = this.Controls.Find("textBox1", true, FirstOrDefault() as TextBox;
tbox.Location = tboxold.Location;
tbox.Size = tboxold.Size;
targetControl.Controls.Add(tbox);
}
}
}
catch (Exception ex)
{
MessageBox.Show((ex.Message));
}
}
Also worth to add:
On the pictures below, the first picture is on tabPage1
of a TabControl
, and second picture is on tabPage2
of the TabControl
where also the flowLayoutPanel
is inside.
Everything works fine, except that it looks really ugly:
If you click into the TextBox
for example, you will see that the text is correct:
The question: How can I fix this ? That everything gets displayed as it should?