2017-03-16 120 views
0

我想在單擊按鈕時動態地將控件添加到面板。但我想組織職位。例如,我想要兩個寬度相等的文本框以相等的面板空間寬度。看下面的圖片。在.NET窗口表格中向TableLayoutPanel添加動態控件

enter image description here

正如你可以在上面的圖片,單擊該按鈕時,控件將被添加看到。但是我在使用TableLayoutPanel時遇到問題。看到我的代碼如下。

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

     } 

正如您在我的代碼中看到的,我評論了我想要做的事情。這些是我的問題。

我想這

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

所以上述方法不起作用。所以我嘗試了一種方法來獲得佈局單元格。但我有問題。看下面的圖片。

enter image description here

正如你在截圖中看到的,我必須要通過子控件來獲取細胞。但我甚至沒有添加控制單元。我想將控制權添加到獲取其各自位置的單元格中。我如何將控制添加到我想要的單元格?

+0

[?如何創建使用Windows窗體幻方(http://stackoverflow.com/questions/ 33968993/how-to-create-a-magic-square-using-windows-forms) –

回答

1

你只需要使用Controls.Add方法,並指定列和行的控制:

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

非常感謝。有效。 :) –

+0

@WayYanHein您的歡迎,下次記得檢查你正在使用的方法超負荷:) –