Question

I am just too confused when it comes to white space. I am trying to padright a string and it won't cooperate with me.

I want to print a datagridview and so I have columns header and below it the actual rows. No matter how I try to determine the exact length or width to pad the string, it is either too short or too long. So, I can't align the values with the column headers before I send to the printer.

if I just do the following for instance:

thestring := '.NET is cool';
thestring := thestring.padright(100); //thestring = too short = '.NET is cool    '

if I do this:

var tmpstr := '=';
tmpstr := tmpstr.PadRight(15); //total length of characters is 15
var swidth := int32(ev.Graphics.Measurestring(tmpstr,new Font('Arial',9)).Width);

thestring := '.NET is cool';
thestring := theString.padright(swidth); //thestring = too long = '.NET is cool   

                '

PadRight or PadLeft seems to work correctly when you pass in actual character not white space, but I could be wrong.

Any input or help will be greatly appreciated.

Était-ce utile?

La solution

There is a difference between each character width when using a proportional font. Arial is a proportional font as are most of the fonts we normally use.

Wikipedia: Typeface

A proportional typeface contains glyphs of varying widths, while a monospaced (non-proportional or fixed-width) typeface uses a single standard width for all glyphs in the font.

What that means is every letter could be a different with. A space does have a width but it will not necessary be the same as the letter "i" or the letter "w".

There are really two options:

  1. You can use a monospace font like Courier New. That will let you use spaces to line up characters based on the letter count.
  2. Use pixel alignments. In that case you need to measure your text width and move the starting location of the text out command so that items line up under each other. You actually calculate the white space that you need and then move to that location instead of padding the string.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top