Hello! I have a question about following code.
I don't understand why workerList gets populated with just 1 record (row) from database (the last one). I used a debugger, and every time new worker is added to workerList in while loop all previous records in list get overriden with last record somehow.
I solved the problem by moving line "Worker w = new Worker();" inside while loop, but I am courious why this thing happens?
For example, if I have 10 different records in database(where {1000, John, Smith} is the last one), this method will return list of 10 records where all of them contain {1000, John, Smith}.
Sorry for bad English, it is not my first language.
public List<Worker> ReturnAllWorkers()
{
List<Worker> workerList = new List<Worker>();
string query = "Select * From TWorker";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
Worker w = new Worker();
while (reader.Read())
{
w.Id = reader["id"].ToString();
w.FirstName = reader["firstname"].ToString();
w.LastName = reader["lastname"].ToString();
workerList.Add(w);
}
conn.Close();
return workerList;
}