Jim Fell
Jim Fell

Reputation: 14256

StringBuilder.AppendFormat Throws Exception

I have an instance of StringBuilder in my C# application wherein I would like certain lines to be padded with a varying number of spaces depending on the context. My usage is very simple:

StringBuilder MyStringBuilder = new StringBuilder();
MyStringBuilder.AppendFormat("{0:" + this._padding + "}"); // <-- Exception thrown here
MyStringBuilder.AppendLine("My data.");

If this._padding==10, the resulting output should look something like this:

     My data.

How can I pad my strings without resorting to using a for loop? Thanks.

ADDITIONAL INFO

Exception: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."

Upvotes: 1

Views: 2398

Answers (8)

Henk Holterman
Henk Holterman

Reputation: 273189

Try

//  AppendFormat("{0:" + this._padding + "}");
    AppendFormat("{0:" + this._padding + "}", "");

A place-holder is holding a place for something.

Exception: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."

0 is greater than or equal to zero but it in this case it was not less than the size of the argument list (0 as well).

Upvotes: 1

mithun_daa
mithun_daa

Reputation: 4384

A lame way of doing it, but should work

for(int i=0; i <this._padding; i++)
{
   MyStringBuilder.AppendFormat("{0}"," ");
}

_padding needs to be an int

Upvotes: -1

Mark Byers
Mark Byers

Reputation: 838096

  • You need to provide both the format and the arguments in one call.
  • To pad left you use {0,10}, not {0:10}.

Try this:

MyStringBuilder.AppendFormat("{0," + this._padding + "}", "My Data");

There is also a string.PadLeft method that you could use.

MyStringBuilder.Append("My Data".PadLeft(this._padding));

Upvotes: 4

Mark Brackett
Mark Brackett

Reputation: 85645

That seems a strange way of doing:

sb.Append(' ', this._padding).AppendLine("My Data");

Upvotes: 2

kol
kol

Reputation: 28688

You cannot simply write something like MyStringBuilder.AppendFormat("{0}"); You must give the variable to be formatted by the format string, like MyStringBuilder.AppendFormat("{0}", "My data");

Upvotes: 1

Erik Dietrich
Erik Dietrich

Reputation: 6090

You can use IEnumerable.Repeat to generate arbitrary numbers of the same string/char.

http://msdn.microsoft.com/en-us/library/bb348899.aspx

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

AppendFormat() expects the data to format as additional argument:

MyStringBuilder.AppendFormat("{0:" + this._padding + "}", "My data.");

Upvotes: 3

SLaks
SLaks

Reputation: 887315

You never passed a parameter for {0} to refer to.

Upvotes: 4

Related Questions