2012-10-05 30 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 
    

您还需要在将表格添加到表单后移动高度检查,否则不会发生布局操作。