string.Format() giving "Input string is not in correct format"

Mr.Rendezvous picture Mr.Rendezvous · Aug 5, 2011 · Viewed 61.7k times · Source

What do I do wrong here?

string tmp = @"
    if (UseImageFiles) {
        vCalHeader += ""<td><img onmousedown='' src= '{0}cal_fastreverse.gif' width='13px' height='9' onmouseover='changeBorder(this, 0)' onmouseout='changeBorder(this, 1)' style='border:1px solid white'></td>\n""; //Year scroller (decrease 1 year)
        calHeight += 22;
    }";

string x = "xter";
tmp = string.Format(tmp, x);

I get

Input string was not in correct format

when trying to change {0}. I am doing this in C# and WinForms.

Format Exception was unhandled
Input string was not in correct format

Troubleshoot tips I get:

Make sure your method arguments are in right format. When converting a string to datetime, parse the string to take out the date before putting each variable into the DateTime object.

Answer

Christian.K picture Christian.K · Aug 5, 2011

string.Format() considers each '{' or '}' to be part of a placeholder (like '{0}' you already use). You need to escape each literal occurrence by doubling it.

So in your case do:

 string tmp = @"
    if (UseImageFiles) {{
        ...
    }}";