Adding dynamic controls to TableLayoutPanel in .NET windows form

旧城冷巷雨未停 提交于 2020-04-14 07:29:27

问题


I want to dynamically add controls to a panel when a button is clicked. But I want to organize the positions. For example I want to have two textboxes side by side equal in width taking the equal space of panel. See the picture below.

As you can see in the picture above, when the button is clicked, controls will be added. But I am having problem with using TableLayoutPanel. See my code below.

private void btnAddOption_Click(object sender, EventArgs e)
        {
            TextBox tb1 = new TextBox();
            tb1.Text = "Cell 1";
            TextBox tb2 = new TextBox();
            tb2.Text = "Cell 2";


            TableLayoutPanel rowLayout = new TableLayoutPanel();
            rowLayout.ColumnCount = 2;
            rowLayout.RowCount = 1;

            //want to add tb1 to cell 1 and tb2 to cell 2 of TableLayoutPanel         

            panelFoodOptions.Controls.Add(rowLayout);

        }

As you can see in my code, I commented what I want to do. These are my issues.

I tried this

rowLayout.Controls.Add(tb1);
rowLayout.Controls.Add(tb2);

So above way does not work. So I tried a way to get the cell of layout. But I am having a problem. See the picture below.

As you can see in the screenshot, I have to pass child control to get the cell. But I haven't even added a control to the cell. I want to add the control to the cell getting its respective position. How can I add control to the cell I want?


回答1:


You just need to use the Controls.Add method and specify column and row for the control:

rowLayout.Controls.Add(tb1, 0, 0);
rowLayout.Controls.Add(tb2, 0, 1);


来源:https://stackoverflow.com/questions/42840406/adding-dynamic-controls-to-tablelayoutpanel-in-net-windows-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!