2012-10-05 40 views
0
 TableLayoutPanel t = new TableLayoutPanel(); 
     t.RowStyles.Add(new RowStyle(SizeType.AutoSize)); 
     t.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); 
     t.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; 
     Label lbl = new Label(); 
     lbl.Margin = new System.Windows.Forms.Padding(20, 150, 20, 20); 
     lbl.Text = "Hello"; 
     t.Controls.Add(lbl, 0, 0); 
     this.Text = t.Size.Height.ToString(); 
     this.Controls.Add(t); 

爲什麼t.Size.Height屬性總是讓我100?TableLayoutPanel高度屬性不工作

+0

如果您不喜歡自動調整大小,請避免將AutoSize設置爲true。 –

回答

4

這始終是返回100的原因是,你需要:

  • AutoSize = true
  • AutoSizeMode =AutoSizeMode.GrowAndShrink
  • t.RowCount >= 1
  • t.ColumnCount >= 1

    TableLayoutPanel t = new TableLayoutPanel(); 
        t.AutoSize = true; //added 
        t.AutoSizeMode =AutoSizeMode.GrowAndShrink; //added 
        t.RowCount = 1; //added 
        t.ColumnCount = 1; //added 
        t.RowStyles.Add(new RowStyle(SizeType.AutoSize)); 
        t.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); 
        t.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; 
        Label lbl = new Label(); 
        lbl.Margin = new System.Windows.Forms.Padding(20, 150, 20, 20); 
        lbl.Text = "Hello"; 
        t.Controls.Add(lbl, 0, 0); 
        this.Controls.Add(t); 
        this.Text = t.Size.Height.ToString(); //moved 
    

您還需要在將表格添加到表單後移動高度檢查,否則不會發生布局操作。