0

So I have to manage a listbox that has columns like table and I would like to give each column a fixed width. I wrote this method to convert the strings into a fixed length:

const int nameMaxWidth = 20;
int nameLength = name.Length;

if (nameLength < 20)
{
   while (nameLength < 20)
   {
      name = name + " ";
      nameLength++;
   }
}
else
{
   name = name.Substring(0, nameMaxWidth);
}

but it seems that it does not work since each letter has different size, for example nnnnn is longer than iiiii although both have the same length. I have tried String.Format but it doesnt work either. Is there anything I can do?

Kise
  • 2,823
  • 1
  • 24
  • 43
  • @JamieRees its WindowsForms – Kise Apr 17 '15 at 14:36
  • 1
    I think you are looking for https://www.bing.com/search?q=c%23+measure+string+width+in+pixels (and [duplicate](http://stackoverflow.com/questions/263614/calculate-the-display-width-of-a-string-in-c) covers some way). If you think that answer does not cover your scenario - make sure to clarify what did not work and specify framework you are using (as solutions are different, especially between desktop and web variations). – Alexei Levenkov Apr 17 '15 at 14:36
  • 1
    @BlameTheBrian this question has been answered. – Jamie Rees Apr 17 '15 at 14:37
  • 1
    The "width" of a `string` depends on the font it's displayed in (and the font size of course). If you know all that, you can try using [Graphics.MeasureString](https://msdn.microsoft.com/library/6xe5hazb.aspx) – Corak Apr 17 '15 at 14:38
  • my bad, I haven't searched with that keywords as I am new to C#. Thank you. – Kise Apr 17 '15 at 14:40
  • I have tried all the methods I could find on the interwebnets, but I have not found any way to get a consistently accurate measurement of a string. I ended up padding the strings with a space at either end to allow for inaccuracies. – Ulric Apr 17 '15 at 14:42
  • @Ulric yeah I don't know why Microsoft does not create an equivalent method to string format in java. The methods used in above answer seems too complicated for a newbie like me :D – Kise Apr 17 '15 at 14:53

0 Answers0