2
votes

I have a C# Windows Form that has a SplitContainer. Inside SplitContainer2 I have a Panel (Panel1). Within that Panel I am creating 10 smaller panels that 5 TextBoxes apiece. I then add each of these panels to Panel1.

for (int i = 1; i < 11; i++)
{
    Panel panel = new Panel();

    TextBox txtBox1 = new TextBox();
    TextBox txtBox2 = new TextBox();
    TextBox txtBox3 = new TextBox();
    TextBox txtBox4 = new TextBox();
    TextBox txtBox5 = new TextBox();

    splitContainer2.Panel1.Controls.Add(panel);
    panel.Controls.Add(txtBox1);
    panel.Controls.Add(txtBox2);
    panel.Controls.Add(txtBox3);
    panel.Controls.Add(txtBox4);
    panel.Controls.Add(txtBox5);
}

In essence I'm trying to create a table with 10 rows and 5 columns. I've tried to do this with a TableLayoutPanel, but couldn't figure it out, so this is my workaround.

I want to provide the ability to allow the user to hit a button "Add New Row" and dynamically create a new Panel with five new textboxes that then gets added as an eleventh row in the "table". The user can keep adding new "rows" as many as they want.

Within my Panel1 I have the Property set to AutoScroll so that when too many "rows" get added it scrolls automatically. For some reason when the "row" is below the scollable Panel an extra space is added and keeps getting added for every new "row" thereafter.

Weird Space

Questions:
1. If I do use the TableLayoutPanel will the same thing happen?
2. What is causing the "extra space" to be added?

EDIT
These following responses are the same as mine, I'm just not having much luck applying it to my solution.

Adding controls to the Panel works the first couple of times, then fritzes out

Dynamic panel element adding and scrollbars

1
@SaghirA.Khatri - This is what this is doing, right? panel.Controls.Add(txtBox1); - Mark
Just as some debugging steps, have you tried adding a border to your panel containing the textboxes to see where the space is being inserted corresponding to the controls? Have you tried grouping your panel + textboxes into a UserControl, and adding just the single control? And this space only appears when the new controls are initially rendered outside the visible area, correct? - Mike Guthrie
@MikeGuthrie - thanks for the input. You are correct that "this space only appears when the new controls are initially rendered outside the visible area, correct?". Let me try the debugging steps and get back to you. - Mark

1 Answers

0
votes

you may need to add new controls to the same panel which you previously added

var penel = splitContainer2.Panel1.Controls.OfType<Panel>().FirstOrDefault();
if(penel !=null)
    penel.Controls.Add(yourNewTextBox);