在.NET Windows窗体中向TableLayoutPanel添加动态控件 [英] Adding dynamic controls to TableLayoutPanel in .NET windows form

查看:57
本文介绍了在.NET Windows窗体中向TableLayoutPanel添加动态控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击按钮时向面板动态添加控件.但我想组织这些职位.例如,我想要两个并排的文本框,其宽度相等,占用面板的相等空间.参见下面的图片.

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.

如上图所示,单击按钮时,将添加控件.但是我在使用TableLayoutPanel时遇到问题.请参阅下面的代码.

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.

我尝试过

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?

推荐答案

您只需要使用

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);

这篇关于在.NET Windows窗体中向TableLayoutPanel添加动态控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆