String.Format throws a System.Format exception in HTML + javascript

I run string.Format on a readonly line that contains some HTML + javascript, but instead I get a System.FormatException .

This is my format string:

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

All I do is pass the name of the object. Like this:

 string.Format(javascript, "grid"); 
+7
string c #
source share
2 answers

Since you have curly braces in a string, you need to avoid them by doubling them ( {{ and }} ) to prevent formatting from thinking that they are tokens.

The line initialization should look something like this:

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

String.Format needs extra brackets to escape. You might be better off doing something like this that might be more readable than escaping each bracket if you don't need all the String.Format functions:

 mystring.Replace("{0}","grid"); 
+6
source share

All Articles