SqlDataReader用它提取的最后一行替换列表条目 [英] SqlDataReader replacing list entries with last row it fetches

查看:111
本文介绍了SqlDataReader用它提取的最后一行替换列表条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我很难过。它正在正确地读取行,我可以看到数据正常,但是当我在最后查看列表时它用最后一行详细信息替换所有数据。例如,它返回10个相同课程的列表。



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.

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

推荐答案

覆盖同一个课程 -object包含您读取的每条记录,并且您的List包含相同的Course-object x次。您需要为每个读取的记录创建一个新的Course对象。
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.


这篇关于SqlDataReader用它提取的最后一行替换列表条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆