138

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.

2 Answers 2

360

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) {{
        ...
    }}";
Sign up to request clarification or add additional context in comments.

1 Comment

A perfect StackOverflow example of Question and Answer, if I ever saw one.
0
  1. Do not combine live braces with escaped braces in the same input string.
  2. If the input string contains any escaped braces, make sure that it is not prefixed with a dollar sign. Otherwise, with escaped left braces, you may get the exception described above. If you only have escaped right braces, one of them may be devoured.

P.S. This advice is based solely on the use of the AppendFormat() method of StringBuilder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.