c# – 如何在生成的列中动态地添加行

我要添加行:

 dtbl = new DataTable();
 dtbl.Columns.Add("Ad.No", typeof(String)); alignment[0] = 'C'; width[1] = 40;
 dtbl.Columns.Add("AdmissionDate", typeof(String)); alignment[1] = 'C'; width[2] = 50;
 dtbl.Columns.Add("Name", typeof(String)); alignment[2] = 'L'; width[3] = 100;
 dtbl.Columns.Add("Class", typeof(String)); alignment[3] = 'C'; width[5] = 40;
 for (int i = model.FromYear; i <= model.ToYear; i++)
 {
   for (int j = model.FromMonth; j <= model.ToMonth; j++)
   {
     for (int k = model.FromDay; k <= model.ToDay; k++)
     {
       dtbl.Columns.Add(Common.CommonUtility.GetShortMonthName(j)+" "+k, typeof(String)); alignment[4] = 'C'; width[5] = 40;
     }
   }

   for (int i = model.FromYear; i <= model.ToYear; i++)
   {
     for (int j = model.FromMonth; j <= model.ToMonth; j++)
     {
       for (int k = model.FromDay; k <= model.ToDay; k++)
       {
         //  dtbl.Rows.Add(dt[j]=std.value);
         //   foreach (var r in std.value){

         dtbl.Rows.Add(dt["Ad.No"] = std.AdmissionNo, dt["AdmissionDate"] = Convert.ToDateTime(std.date.ToString()).ToString("dd/MM/yyyy"), dt["Class"] = std.Class, dt["Name"] = std.StudentName,dt[j]=std.value);
       }
     }

我必须在列单元格中添加行,如p A p A.

最佳答案 创建列时,列名称也可以包含唯一的年份:

private GetColumnName(int year, int month, int day)
{
  return year.ToString() + " " + Common.CommonUtility.GetShortMonthName(month) + " " + day;
}

如果std包含一个日期的值,那么如果std记录也提供了此日期(或三个属性year,month,day),则会有所帮助.

然后,从DB加载的std列表可以按行标识符(是Ad.No?)进行分组,并处理每个组以填充一行:

var stdList = ... select from DB;

var stdGroups = stdList.GroupBy(x => x.AdmissionNo);

foreach(var group in stdGroups)
{
  var stds = group.ToList();

  var row = dtbl.NewRow(); // a new row of untyped data table
  row["Ad.No"] = stds.First().AdmissionNo;
  // ...set also the other properties

  for (int i = model.FromYear; i <= model.ToYear; i++)
  {
    for (int j = model.FromMonth; j <= model.ToMonth; j++)
    {
      for (int k = model.FromDay; k <= model.ToDay; k++)
      {
        var std = stds.Single(x => x.Year == i && x.Month == j && x.Day == k);
        row[GetColumnName(i,j,k)] = std.value;

       }
     }
  }

  dtbl.Rows.Add(row);
}
点赞