如何按按钮名称长度调整标签大小

问题描述 投票:0回答:1

我正在尝试动态创建按钮和标签,创建很好但是调整标签的大小是有问题的,我想按按钮名称长度缩放标签大小但调整大小不起作用,我的代码和屏幕截图输出在下面,你能帮我吗?请?

for (int i = 0; i < 10; i++)
{


    Button btn = new Button();
    btn.Name = "btnAdi" + (i + 1).ToString();
    btn.Text = (i + 1).ToString();
    this.Controls.Add(btn);
    btn.Location = new Point(0, btn.Height * i);

    Label lbl = new Label()
    {
        TextAlign = ContentAlignment.MiddleLeft,
        Dock = DockStyle.None,
        BorderStyle = BorderStyle.FixedSingle,
    };
    lbl.Text = btn.Name.ToString();

    lbl.Size = new Size( (btn.Name.Length), btn.Height);
    this.Controls.Add(lbl);
    lbl.Location = new Point(btn.Width, (btn.Height * i));


}

screenshot of output

c# winforms label size
1个回答
2
投票

你只需要自动标记标签,如下所示:

编辑:

关注@Malior注释,使用自动调整大小,您可以删除“lbl.Size”行。

for (int i = 0; i < 10; i++)
{
    Button btn = new Button();
    btn.Name = "btnAdi" + (i + 1).ToString();
    btn.Text = (i + 1).ToString();
    this.Controls.Add(btn);
    btn.Location = new Point(0, btn.Height * i);

    Label lbl = new Label()
    {
        TextAlign = ContentAlignment.MiddleLeft,
        Dock = DockStyle.None,
        BorderStyle = BorderStyle.FixedSingle,
    };
    lbl.AutoSize = true;
    lbl.Text = btn.Name.ToString();

    this.Controls.Add(lbl);
    lbl.Location = new Point(btn.Width, (btn.Height * i));
}

输出:

enter image description here

Aaditi:

如果你想要属性“lbl.Size”你需要这样的东西来获得lbl.Text的宽度:

Font arialBold = new Font("Arial", 10);
Size size = TextRenderer.MeasureText(lbl.Text, arialBold);
lbl.Size = new Size(size.Width, size.Height);

我已经注意到这个方法给出了1或2个空格,这也是我认为的。

输出2:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.