James Couvares
James Couvares

Reputation: 1783

string.Format throws System.Format exception on HTML + javascript

I'm running string.Format on a readonly string that contains a bit of HTML + javascript but I get a System.FormatException instead.

This is my format string:

<script type="text/javascript">
    function {0}_showHideFieldWindow() {
        if ({0}.IsCustomizationWindowVisible()) {
            {0}.HideCustomizationWindow();
        } else {
            {0}.ShowCustomizationWindow();
        }
    }
</script>

All i'm doing is passing in the object name. Like this:

string.Format(javascript, "grid");

Upvotes: 7

Views: 6485

Answers (2)

Keltex
Keltex

Reputation: 26436

String.Format needs the extra brackets to be escaped. You might be better off doing something like this, which might be more readable than escaping each bracket if you don't need all of String.Format's functionality:

mystring.Replace("{0}","grid");

Upvotes: 6

Andrew Hare
Andrew Hare

Reputation: 351616

Since you have curly braces in the string you need to escape them by doubling them up ({{ and }}) to prevent the formatter from thinking they are tokens.

Your string initialization should look something like this:

String javascript = @"<script type=""text/javascript"">
            function {0}_showHideFieldWindow() {{
            if ({0}.IsCustomizationWindowVisible()) {{
                {0}.HideCustomizationWindow();
            }} else {{
                {0}.ShowCustomizationWindow();
            }}
        }}
    </script>";

Upvotes: 12

Related Questions