I'm facing a problem adding data to an IList
but the problem is each time I added data the existing data is overwritten with the current one my code is given below:
Test test = new Test();
IList<Test> myList = new List<Test>();
foreach (DataRow dataRow in dataTable.Rows)
{
test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
test.LastName = dataRow.ItemArray[1].ToString();
test.FirstName = dataRow.ItemArray[2].ToString();
myList.Add(test);
}
What's the reason behind this?
move test object creation inside the loop
IList<Test> myList = new List<Test>();
foreach (DataRow dataRow in dataTable.Rows)
{ Test test =new Test();
test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
test.LastName = dataRow.ItemArray[1].ToString();
test.FirstName = dataRow.ItemArray[2].ToString();
myList.Add(test);
}
what you currently doing is updating same instant of test
inside the loop and add the same again and again..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With