Nagesh
Nagesh

Reputation: 1308

string.Format(): Format string by taking the width at run time C#.net 2.0

In normal string format we would write like this:
string formattedString = string.Format("{0, -30}", someData.ToString());
It formats the string 30 characters left aligned.

I wish to format strings of different varying widths and this width would be specified at run time. In above example I would pass width (30, 50, 60, etc.,) as parameter.

Pls help me to acheive this.

Upvotes: 1

Views: 806

Answers (2)

xanatos
xanatos

Reputation: 111860

int alignment = 30;
string format = "{0, -" + alignment + "}";
string formattedString = String.Format(format, someData);

You don't need the ToString in many places. It's called by the String.Format and similar methods.

Upvotes: 0

msarchet
msarchet

Reputation: 15242

String formattedString = 
  String.Format("{0, -" + someData.ToString.Count() + "}", someData.ToString());

Without having to call someData.ToString() twice as it could be expensive.

String someDataString = someDate.ToString();
String formatteString = 
  String.Format("{0, -" + someDataString.Count() + "}", someDataString);

Upvotes: 3

Related Questions