[Solved] How to set auto size the dynamic label box text in c#? [closed]


Short answer:

dynamiclabel.MaximumSize = new System.Drawing.Size(900, 26);

Explanation: The best way is to use a combination of AutoSize = true and a suitable MaximumSize: The layout in your form or container will set some limit of how wide the Labels are allowed to grow. If you don’t control this they will grow to the right unlimited.. So setting that limit, taking into account space for scrollbar, padding, margins and some slack will give you the number to use in the MaximumSize property.

Let’s add a couple of questions into a FlowLayoutPanel for easiest layout:

for (int q = 0; q < 50; q++) addQuestion(flowLayoutPanel1, q + 1);

Here is the routine that creates a question consisting of two labels:

void addQuestion(FlowLayoutPanel flp, int nr)
{
    Label l1 = new Label();
    l1.AutoSize = true;
    l1.Font = new System.Drawing.Font("Consolas", 9f, FontStyle.Bold);
    l1.Text = "Q" + nr.ToString("00") + ":";
    l1.Margin = new System.Windows.Forms.Padding(0, 5, 10, 0);
    flp.Controls.Add(l1);

    Label l2 = new Label();
    l2.Text = randString(50 + R.Next(150));
    l2.Left = l1.Right + 5;
    l2.AutoSize = true;
    l2.Margin = new System.Windows.Forms.Padding(0, 5, 10, 0);
    // limit the size so that it fits into the flp; it takes a little extra
    l2.MaximumSize = new System.Drawing.Size(flp.ClientSize.Width - 
           l2.Left - SystemInformation.VerticalScrollBarWidth  - l2.Margin.Right * 2, 0);
    flp.Controls.Add(l2);
    flp.SetFlowBreak(l2, true);
}

I use a tiny random string generator:

Random R = new Random(100);
string randString(int len)
{
    string s = "";
    while (s.Length < len) s+= (R.Next(5) == 0) ? " " : "X";
    return s.Length + " " + s + "?";
}

enter image description here

If you want to make the containersize dynamic just code the resize event to adapt the MaximumSize of the questions:

private void flowLayoutPanel1_Resize(object sender, EventArgs e)
{
    flowLayoutPanel1.SuspendLayout();
    int maxWidth = flowLayoutPanel1.ClientSize.Width  - 
                   SystemInformation.VerticalScrollBarWidth ;
    foreach (Control ctl in flowLayoutPanel1.Controls )
    {
        if (ctl.MaximumSize.Width != 0)
           ctl.MaximumSize = new Size(maxWidth - ctl.Left - ctl.Margin.Right * 2, 0);
    }
    flowLayoutPanel1.ResumeLayout();
}

This will adapt the layout for all question labels..:

enter image description here

solved How to set auto size the dynamic label box text in c#? [closed]