String.Format: Input string was not in a correct format

jamesdeath123 picture jamesdeath123 · Jan 29, 2013 · Viewed 34.3k times · Source

The following code keep giving me error saying Input string was not in a correct format, but I am pretty sure it is right, isn't it?

int id = 112;

String[] newData = { "1", "2", "21", "reidb", "reidb", "reidb", "reidb", "aa", 
                      "Some description", "11", "2012-02-28", "2012-01-29", "true", "1", "1", 
                      "true", "note note note", "true", "1", "2011-12-03", "45"};

String data = "{ cmd: \"save magellan deal\", data: { id: {0} , AId: {1}, " +
            "CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
            "LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
            "dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
            "period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},} " +
            "Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} } }";


String cmd = String.Format(data, id.toString(), newData);

Anyone any ideas?

=== EDIT ===

after fixing the braces, a new error of "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." is given. the newData has 21 and plus the id.toString(), should be exact 22?

Answer

Cédric Bignon picture Cédric Bignon · Jan 29, 2013

Escape the "{", "}" (by duplicating them) in the format string:

"{{ cmd: \"save magellan deal\", data: {{ id: {0} , AId: {1}, " +
"CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +
"LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +
"dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +
"period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +
"Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} }} }}"

And you have 22 elements in the format string and 21 in the array.