Format a string into columns

You can specify the number of columns occupied by the text as well as alignment using Console.WriteLine or using String.Format:

// Prints "--123       --"
Console.WriteLine("--{0,-10}--", 123);
// Prints "--       123--"
Console.WriteLine("--{0,10}--", 123);

The number specifies the number of columns you want to use and the sign specifies alignment (- for left alignment, + for right alignment). So, if you know the number of columns available, you could write for example something like this:

public string DropDownDisplay { 
  get { 
    return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
      Name, City, State, ID);
  } 
} 

If you’d like to calculate the number of columns based on the entire list (e.g. the longest name), then you’ll need to get that number in advance and pass it as a parameter to your DropDownDisplay – there is no way to do this automatically.

Leave a Comment