Accurately placing multiple controls in a row programmatically with dynamic table layout panel

61 Views Asked by At

I have made a gui that correctly positions a checkbox and label controls to the form but read on here that to add scrolling the controls should be in a tableLayoutPanel and here using the same code is wrong. I have tried myriad ways to adapt the code and have now got in a mess with it, I am sure its a basic oversight but I cannot spot it.

Code without tableLayoutPanel

    int X = 1;
    string s = "i=";
    private void btnAddItem_Click(object sender, EventArgs e)
    {
        for (int i = 1; i <= X; i++)
        {
            //make the objects for list items
            Label lbl = new Label();
            CheckBox cb = new CheckBox();
       
            lbl.Location = new Point(50, 75 * (i ));
            cb.Location = new Point(30, 75 * (i ));

            lbl.Text = s + i.ToString() + "  " + lbl.Location.ToString();
            //lbl.Text = txtBoxInput.Text;
            Controls.Add(lbl);
            Controls.Add(cb);
        }
        X++;
        txtBoxInput.Clear();
    }

Snippet of desired performance from above code - works as desired

Code with TableLayoutPanel not working as desired

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        createTableLayoutPanel();
    }

    int count = 1;
    int X = 1;
    string s = "i=";
    TableLayoutPanel table = new TableLayoutPanel();

    private void createTableLayoutPanel() 
    {
        

        table.ColumnCount = 2;
        table.RowCount = 0;
        table.BackColor = Color.Khaki;
        table.Size = new System.Drawing.Size(300, 400);
        table.Location = new Point(50, 100);
        table.AutoScroll = true;

        Controls.Add(table);
    }

    private void btnAddItem_Click(object sender, EventArgs e)
    {
        //TableLayoutPanel tlp = this.table;
        for (int i = 1; i <= X; i++)
        {

            //make the objects for list items
            Label lbl = new Label();
            CheckBox cb = new CheckBox();

            table.SuspendLayout();
            //table.GrowStyle = TableLayoutPanelGrowStyle.AddRows;
            //table.RowCount = table.RowCount + 1;
            //table.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));

            table.Controls.Add(cb, 0, i);

            lbl.Text = "i=" + i.ToString() + " " + txtBoxInput.Text + "  X=" + X.ToString();
            table.Controls.Add(lbl, 2, i);
            table.ResumeLayout();
        }
        X++;
        
        txtBoxInput.Clear();
    }
}

Snippet of the undesired result with TLP used

Desired behaviour When Add item is clicked a row should be added to the top of the TLP and move any existing rows downwards. Checkbox always on the left, label always on the right.

0

There are 0 best solutions below