Why does Visual Studio say my input string is not in a correct format?

The following code:

string year = textBoxYear.Text;
string award = comboBoxAwards.Text;
string cat = comboBoxCategory.Text;
string title = textBoxTitle.Text;
string author = textBoxAuthor.Text;
string kindleASIN = textBoxKindleASIN.Text;
string hardboundASIN = textBoxHardboundASIN.Text;
string paperbackASIN = textBoxPaperbackASIN.Text;
string imgSrc = getImgSrc(kindleASIN, hardboundASIN, paperbackASIN);
string newRec = // Keeping year as int for LINQ querying (where year > or < such and such), and yearDisplay spans two years for some awards
    string.Format(
        "new BookClass{Award=\"{0}\", Year={1}, YearDisplay=\"{1}\", Category=\"{2}\", Title=\"{3}\", Author=\"{4}\", KindleASIN=\"{5}\", HardboundASIN=\"{6}\", PaperbackASIN=\"{7}\", ImgSrc=\"{8}\"},", award, year, cat, title, author, kindleASIN, hardboundASIN, paperbackASIN, imgSrc);

...using this data:

year = "2013"
award = "Hugos"
cat = "Best Novel"
title == "Redshirts"
author == "John Scalzi"
kindleASIN == "B0079XPUOW"
hardboundASIN == "0765316994"
paperbackASIN == "0765334798"
imgSrc == "http://images.amazon.com/images/P/B0079XPUOW.01.MZZZZZZZ"

...dies on the assignment to imgSrc, saying: "System.FormatException was unhandled HResult=-2146233033 Message=Input string was not in a correct format".

...and the "Troubleshooting tips" says, "When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object."

But I'm not converting a string to DateTime...What could be the problem?

Upvotes: 1

Views: 988

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

Your curly braces that are not replacement tokens are messing it up

new BookClass{Award=\"{0}\", Year={1}, YearDisplay=\"{1}\"
      here --^

You need to escape any { or } you use by doubling them, they will show up as a single curly brace after the Format function processes the string.

string.Format(
        "new BookClass{{Award=\"{0}\", Year={1}, YearDisplay=\"{1}\", Category=\"{2}\", Title=\"{3}\", Author=\"{4}\", KindleASIN=\"{5}\", HardboundASIN=\"{6}\", PaperbackASIN=\"{7}\", ImgSrc=\"{8}\"}},", award, year, cat, title, author, kindleASIN, hardboundASIN, paperbackASIN, imgSrc);

Upvotes: 6

Related Questions