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;
        }

I get it now. list.Add() method does not create copy of passed Worker record. Sorry for bothering you :)

Could be because you are adding the same memory location to the workerlist with the Add and thus when you alter that memory location to another value then the workerlist will able be altered as well.. I am guessing..

probably best to do something like

while (reader.Read())
{
Worker w = new Worker();
....
workerList.add(w);
}

at a guess.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.