Format String

  • Thread starter Thread starter PawelR
  • Start date Start date
P

PawelR

Hello Group,
In my apps I formating string:
String.Format("{0,-15}{1,-10}{2,-25}{3,-25}",myTable)
How change width column in code.
Column width must be more that length string in table.
I know how is max length string in myTable.

this code is incorect
int a = -15;
String.Format("{0,-a}{1,-10}{2,-25}{3,-25}",myTable)
Error: incorect string format


Thx PawelR
 
PawelR said:
Hello Group,
In my apps I formating string:
String.Format("{0,-15}{1,-10}{2,-25}{3,-25}",myTable)
How change width column in code.
Column width must be more that length string in table.
I know how is max length string in myTable.

this code is incorect
int a = -15;
String.Format("{0,-a}{1,-10}{2,-25}{3,-25}",myTable)
Error: incorect string format

I don't believe there's any way of specifying in a format string that a
precision indicator (or whatever) is derived from a parameter. You
could use String.PadLeft and String.PadRight when specifying the
parameter itself, of course.
 
One solution (and I'm not claiming it is the best, it does have it's
caveats) would be to create the format string dynamically as needed. This
would probably mean cycling through the structure twice, once to find the
max values in each column, another to write the string out in the
appropriate format.

What I would do is store the information about the max string length for
each column in an array. The array would basically have the same number of
elements as there are rows. Each element in the array would be an index to
the number of the row. The first element in the array would have the
smallest sized value, the next would have next largest value, and so on, and
so on. When you add a new row, you have to insert a new element into this
array (and in the right place) for each column. When you delete a column,
you have to remove the element. When you edit a column, you have to change
the location of the element in the array.

When you have to write this information out, creating the format string
is then easy, you just take the values from the last element of each array
that corresponds to the column, and then use that for the precision.

Hope this helps.
 
Back
Top