Click here to Skip to main content
15,900,417 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This has me stumped. It is reading the rows properly, I can see the data coming in fine, but when i view the list at the end it replaces all the data with the last row details.. For example it returns a list of 10 of the same courses.

C#
<pre>/// ********************************************************************
        /// <summary>
        /// Get details of all upcoming courses.
        /// </summary>
        /// ********************************************************************
        public List<Course> GetUpcomingCourses(Course c)
        {
            List<Course> courseList = new List<Course>();

            con.ConnectionString = conString;
            con.Open();

            try
            {
                using (con)
                {
                    SqlCommand cmd = new SqlCommand(GetUpcomingCoursesCommandText, con);
                    SqlDataReader rd = cmd.ExecuteReader();

                    while (rd.Read())
                    {
                        c.CourseID = Convert.ToInt32(rd["CourseID"]);
                        c.Name = Convert.ToString(rd["Name"]);
                        c.Date = Convert.ToDateTime(rd["Date"]);
                        c.StartTime = Convert.ToString(rd["StartTime"]);
                        c.EndTime = Convert.ToString(rd["EndTime"]);
                        c.Description = Convert.ToString(rd["Description"]);
                        c.Location = Convert.ToString(rd["Location"]);

                        courseList.Add(c);
                    }
                }
            }
            finally
            {
                con.Close();
            }

            return courseList;
        }
Posted

1 solution

You overwrite the properties of one and the same Course-object with every record you read and your List contains the same Course-object x times. You need to create a new Course-object for every record read.
 
Share this answer
 
Comments
Maciej Los 16-May-15 6:36am    
Sascha, you took the words out of my mouth... ;)
Sascha Lefèvre 16-May-15 6:43am    
;-)
I'll get back to writing my first article (or maybe just a tip/trick) now, so your words will be safe for now ;-)
Maciej Los 16-May-15 6:51am    
;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900