I am going through the rows of an excel file and increasing the row to go to the next row, it should be clarified that the excel file reads each cell of each row correctly, what happens is that when it reaches Add(info)
each row
it should be added, and that is that When the first one is read, everything is fine. At the end, it remains saved, but when it advances to the next row and reads the data, these data are saved, but the previous one that was saved is lost, and so on.
When it arrives at Save()
what it is function
to do a insert
to the DB with a foreach
I go through the list with all the rows, and if it brings me all the rows but in all it is the last one that was read, that is to say; If I have 100 rows that should be different, the 100 rows are the last and have the same information.
public string RecorrerExcel()
{
DataTable excelTable = new DataTable("ExcelFile");
DataTable original = GetDataTableExcel();
int renglon = 1;
ExcelInformation info = new ExcelInformation();
List<ExcelInformation> listaInformation = new List<ExcelInformation>();
foreach (DataRow item in original.Rows)
{
for (int i = 0; i < original.Columns.Count; i++)
{
//
switch (original.Rows[0][i].ToString())
{
case "XXXXX":
info.XXXXX = item[i].ToString();
break;
case "XXXXX":
info.XXXXX = item[i].ToString();
break;
case "XXXXX":
info.XXXXX = item[i].ToString();
break;
case "XXXXX":
info.XXXXX = item[i].ToString();
break;
case "XXXXX":
info.XXXXX = item[i].ToString();
renglon += 1;
break;
default:
break;
}
}
Add(info); //agrega a la lista
}
Save(); //function para hacer insert
return "";
}
You are saving in the list the reference to the same instance of info .
To fix this, you need to create a new instance of info inside the loop...
As above, the list will not contain references to the same instance.