0

I use Winform, and I have many Label line up as ListView. The Label have three contents in a row, I hope I can have some method to let each content same width. I have tried PadRight, but it isn't really solve the problem, if the content is Full-width, then calculate the string.length isn't useful.

My Label is dynamically created, like this:

int lineheight=24;
for(int i=0; i<40;i++){
    Label test = new Label();
    test.Name = "test" + i;
    test.Text = padLength(str1, 16) + padLength(str2, 27) + padLength(str3, 10); // str1~str3 is data that user input in another user control
    test.AutoSize = false;
    test.Top = 10 + lineheight * i;
    test.Left = lineheight;
    test.Width = panel1.Width - lineheight;
    test.Height = lineheight;
    test.Font = new System.Drawing.Font("Arial", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
    panel1.Controls.Add(test);
}

and the function padLength is what I need to let the string be same width, like:

 private string padLength(string str,int len)
{
    string tmp = str;

    for (int i = 0; i < len; i++)
    {
        if (tmp.Width != len)
        {
            tmp = tmp + " ";
        }
    }
    return tmp;
}

Because I need to move the control( by a custom slide bar), I only use one Label to present the three contents( I have tried use three Label for each other, and the result is lower the speed of control moving).

I know there is a way to measure the string width use MeasureString(), but I'm not sure how to use it( because it use the Graphic class)......

Any advice appreciate.

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Shuinvy
  • 251
  • 2
  • 6
  • 23
  • 1
    `Pad` functions in my experience only really work on monospaced fonts.. what you could do is just put the 3 labels inside a box and then move the box, so you still only have 1 control to move – Sayse May 19 '14 at 06:51
  • Wow, it worked! But I still curious if there is any method that can make string same width. If there isn't, I still want to know the reason...... – Shuinvy May 19 '14 at 08:02
  • 1
    The strings, not really as its a little bit cumbersome to get the length of the string, including the font size, you could get the labels the same width by taking the largest label width, and then applying this width to the other labels. Would then probably need to center the text. Edit: Heres an example of [how to use MeasureString](http://stackoverflow.com/a/11909436/1324033) – Sayse May 19 '14 at 08:13

0 Answers0