I know that this has been asked before and I have tried my best to find an answer that could help me with my problem - but with no succes. I apoligize for the duplicated question but I hope you still want to help me out.
Thanks in advance!
I have made a solution where I can upload a csv file into my sql database. When I run the code, choose the file and presses "Upload" I get the following error: "Input string was not in a correct format."
The error is being thrown in my controller at; LearningNumbers.LearningNumberId = int.Parse(values[0]);
My CSV
LearningNumberId;Note;Activity;Price
1;Node1;her er node 1;22
2;Node1;her er node 2;33
My model:
namespace MTH_SQL.Model
{
public class LearningNumberRecord
{
[Key]
public int LearningNumberId { get; set; }
public string Note { get; set; }
public string Activity { get; set; }
public int Price { get; set; }
}
}
My controller:
namespace MTHoejgaard.Controllers
{
public class HomeController : Controller
{
private MTHoejgaardContext db = new MTHoejgaardContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase File)
{
if (File != null && File.ContentLength > 0)
{
StreamReader csvReader = new StreamReader(File.InputStream);
{
string inputLine = "";
while ((inputLine = csvReader.ReadLine()) != null)
{
string[] values = inputLine.Split(new Char[] { ';' });
LearningNumberRecord LearningNumbers = new LearningNumberRecord();
LearningNumbers.LearningNumberId = int.Parse(values[0]); // <-- IT THROWS THE ERROR HERE
LearningNumbers.Note = values[1];
LearningNumbers.Activity = values[2];
LearningNumbers.Price = int.Parse(values[3]);
db.LearningNumbers.Add(LearningNumbers);
db.SaveChanges();
}
csvReader.Close();
}
}
return RedirectToAction("Index");
}
}
My View:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="File" id="File" />
<input type="submit" name="Submit" value="Upload" />
<span>@ViewBag.Message</span>
}
Change your CSV file to this (first line removed):
1;Node1;her er node 1;22
2;Node1;her er node 2;33
Alternatively, jump the first line when parsing the file.