table 的列宽不正确

Column width of table not correctly

因为我是新手,所以当我想为 table 的列宽设置值时遇到问题(使用代码 C#)

我要像图片一样参展

但是当我编码时:

    private void Form1_Load(object sender, EventArgs e)
    {
       // TableLayoutPanel tableLayoutPanel = new TableLayoutPanel();

        tableLayoutPanel.ColumnCount = 3;
        tableLayoutPanel.RowCount = 1;

        tableLayoutPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.OutsetDouble;
        tableLayoutPanel.Dock = DockStyle.Top;
        tableLayoutPanel.Height = 100;

        tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10F));
        tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 60F));
        tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));

        #region Create Label1, label2, label3         
        Label label1 = new Label();
        label1.Text = "Width 10%";
        //label1.Dock = DockStyle.Fill;  

        Label label2 = new Label();
        label2.Text = "Width 60%";
        //label1.Dock = DockStyle.Fill;

        Label label3 = new Label();
        label3.Text = "Width 30%";
        //label1.Dock = DockStyle.Fill;
        #endregion 

        tableLayoutPanel.Controls.Add(label1, 0, 0);
        tableLayoutPanel.Controls.Add(label2,1,0);
        tableLayoutPanel.Controls.Add(label3, 2, 0);
    }

列宽不正确,如下所示

我不知道为什么。请告诉我以及如何解决它。 感谢阅读

您的 collection 中可能已有 ColumnStyles。设置 ColumnCount 不会重置 collection。在添加新的之前简单地清除它:

tableLayoutPanel.ColumnStyles.Clear();
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10F));
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 60F));
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));