Click here to Skip to main content
15,878,814 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
AAAAAARRRRGGGH! I'm going out of my mind.

I'm simply trying to do this:

C#
string result = string.Format(htmlText, plainTexts);


where

C#
htmlText = @"{0}<tr style="padding: 0; border-removed 0"><td style="padding: 0; border-removed 0; width: 75px">{1}</td><td style="padding: 0; border-removed 0">{2}</td></tr>";


And plainTexts is a List of string containing 3 elements:

C#
plainTexts[0] = "   ";
plainTexts[1] = "foo";
plainTexts[2] = "bar";


and I get this exception in the string.Format line:

Unhandled Exception: System.FormatException:
    Index (zero based) must be greater than or equal to zero and less
    than the size of the argument list.


WHY WHY WHY? I've got three placeholders, correctly numbered and a list of three arguments. As far as I can see, everything is in perfect working order.

WHAT AM I MISSING???
Posted
Comments
V. 9-Mar-15 5:34am    
htmlText? The quotes are not escaped and the strings not concatenated. But that could be the format on CP of course. (likely, because that wouldn't compile, right?)
Johnny J. 9-Mar-15 5:36am    
The quotes are escaped (that's what @ does), but this is only an example. I'm not entering the html text manually in code like above, I'm parsing them from a webbrowser source, and they are valid strings...

1 solution

This worked for me:
C#
string htmlText = @"{0}<tr style="" border-removed="" 0=""><td style="" border-removed="" 75px="">{1}</td><td style="" border-removed="" 0="">{2}</td></tr>";
string[] plainTexts = new string[3];
plainTexts[0] = "   ";
plainTexts[1] = "foo";
plainTexts[2] = "bar";
string result = string.Format(htmlText, plainTexts);
 
Share this answer
 
Comments
Johnny J. 9-Mar-15 5:39am    
You're using a string array, I'm using a genereic list of strings. But even if I do a plainTexts.ToArray(), it still doesn't work for me.
[no name] 9-Mar-15 5:42am    
ok letme try with list
Johnny J. 9-Mar-15 5:43am    
Correction: It DOES actually work with an array of string if I do ToArray(), but I get a warning from VS: Co-variant array conversion from string[] to object[] can cause run-time exception on write operation
[no name] 9-Mar-15 5:52am    
Try this:
string result = string.Format(htmlText, plainTexts.Cast<object>().ToArray());

warning is about the implicit conversion of string[] to object[].
Johnny J. 9-Mar-15 5:54am    
Cool. That took care of the warning! Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900