List.Add() 的问题:它只显示最后一行

Issue with List.Add(): it only displays the last row

List.Add()的问题:它只保存最后添加的项目,它重复绑定最后的数据,请有人帮我清除它。我正在 mvc 4 中尝试作为初学者。我也在为 mvc 4 的基础而苦苦挣扎。提前谢谢你。

var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=@batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
    var model = new MyCourseData();                  
    var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
    int j = 0;
    // string[] parts = classdates.Split(',');
    foreach (string CourseDates in classdates.Split(','))
    {
         model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
         model.course = ds.Tables[0].Rows[i]["course"].ToString();
         model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
         model.class_dates = CourseDates;
         modelList.Add(model);

    }

}
return modelList;

发生这种情况是因为您在列表中添加了相同的 MyCourseData 实例,并且每次迭代的值都在变化。 您需要为每次迭代创建新的 MyCourseData 实例,

var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=@batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{

    var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
    int j = 0;
   // string[] parts = classdates.Split(',');
     foreach (string CourseDates in classdates.Split(','))
     {
        var model = new MyCourseData();                  
        model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
        model.course = ds.Tables[0].Rows[i]["course"].ToString();
        model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
        model.class_dates = CourseDates;

        modelList.Add(model);

     }

}
return modelList;
}