Search code examples
c#winformslabelvertical-alignment

How do I push down control


I have a label with variable-length text and a progressBar below to it. I want to keep a space between that label and the progressBar, so depending to label's text(which is wrapped) the progressBar should be pushed down, always keeping the space between them. How should I do that? I tried AutoSize = true and AutoSizeMode = GrowAndShrink but it didn't changed anything. Example:

 ---------------------------
|  for example the label's  |
|  text might be something  |
|  like this, with a lot of |
|  of text but the progress |
|  bar should be here       |
|                           |
| progressBar here          |
 ---------------------------

example 2:

 ---------------------------
|  small text               |
|                           |
| progressBar here          |
 ---------------------------

Solution

  • Put the Label and the ProgressBar into a FlowLayoutPanel that has its FlowDirection property set to TopDown. Now when the Label grows vertically the ProgressBar will be pushed down automatically. To control the distance between the Label and the ProgressBar, change the Bottom value in the Padding property of the Label.

    Here's what my form looks like after hitting the button a couple times with AutoSize set to true on the Form and the FlowLayoutPanel (using GrowOnly in AutoSizeMode):

    enter image description here

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            for(int i = 1 ; i < 20; i++)
            {
                label1.Text = label1.Text + " more ";
            }
        }
    }