2016-08-02 64 views
1

開始時有一個TableLayoutPanel只有一行而沒有列。通過按下按鈕,我希望這個面板可以用5行和3列進行轉換。如何以編程方式在TableLayoutPanel上應用列和行樣式?

private void button_Click(object sender, EventArgs e) 
    { 
     this.tableLayoutPanel1.ColumnCount = 3; 
     this.tableLayoutPanel1.RowCount = 5; 
    } 

問題是,你得到這個結果!

enter image description here

與該行和列創建的框不包含相同的區域在面板上,你可以看到。

在3列和5行的情況下,列必須共享tablelayoutpanel的100%,因此每個列必須共享30%。在5行的情況下,每行必須佔20%。

所以我追加到button_Click方法接下來的兩行代碼。

this.tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F)); 
this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 20F)); 

但我得到了同樣的結果! 我缺少什麼?

+1

爲什麼你需要空的'TableLayoutPanel'?只需將控件添加到它(請參閱[此答案](http://stackoverflow.com/a/12687222/1997232))。屏幕截圖與您的代碼不匹配。考慮準備[mcve](http://stackoverflow.com/help/mcve)(以分步指南或Form1.cs + Form1.designer.cs的完整轉儲的形式),然後有人可以嘗試更仔細地研究你的問題。 – Sinatr

回答

2

可能您正在將樣式添加到已定義的TableLayoutPanel而不重置當前樣式。

tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; 
tableLayoutPanel1.Dock = DockStyle.Fill; 

tableLayoutPanel1.Controls.Clear(); 
tableLayoutPanel1.ColumnStyle.Clear(); 
tableLayoutPanel1.RowStyle.Clear(); 

tableLayoutPanel1.RowCount = 5; 
for(int x = 0; x < tableLayoutPanel1.RowCount; x++) 
    tableLayoutPanel1.RowStyles.Add(new RowStyle() { Height = 20, SizeType = SizeType.Percent }); 
tableLayoutPanel1.ColumnCount = 3; 
for(int x = 0; x < tableLayoutPanel1.ColumnCount; x++) 
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle() { Width = 33, SizeType = SizeType.Percent }); 
相關問題