DataTable多列合并问题轻松搞定

问题背景

  在做考试系统手动生成试卷部分时由于题库的表结构不相同,导致同样的Gridview(已模板化后的,其结构已固定)在显示时不能同时两种不同结构的数据。如GridView结构如下所示:

DataTable多列合并问题轻松搞定

  这种固定的格式显示的是以选择题为代表的数据结构,但是因为选择题题库表结构与论述题题库表结构不相同,所以无法直接显示以论述题为代表的数据结构。这时如何在这个固定的GridView中显示不同的数据呢?其实在仔细观察后我们可以发现他们唯一的区别在于“答案”这列的数据不同,在选择题类型中,该字段的值仅为一个选项而已,但是对于论述题等类型,其问题有六个,对应的答案也应该有六列才对。分析到此,可以总结一下,最终要解决的问题是如何将六列的答案显示在一列。

  解决办法:将六个字段中的内容用sql语句实现合并,将其作为一个新的字段显示出来,具体的实现请看代码:

  

复制代码 代码如下:

  #region 根据动态生成的数据库表名,从该表中选出QuestionId,ChapterId,QuestionTypeId,Point,不包括难度等级约束

  /// <summary>

  /// 根据动态生成的数据库表名,从该表中选出QuestionId,ChapterId,QuestionTypeId,Point,

  /// Degree,Fraction,QuestioinContent,IsValid等内容,不包括难度等级约束

  /// </summary>

  /// <param name="strDataTableName"></param>

  /// <returns></returns>

  public DataTable BindQuestion(string strTableName,string strChapterName,string strQuestionTypeName)

  {

  try

  {

  DataTable dt = new DataTable ();

  if (strQuestionTypeName != "论述题" && strQuestionTypeName != "案例分析题")

  {

  strsql = "select * from " + strTableName + " where ChapterId=@chapterid and QuestionTypeId=@questiontypeid";

  }

  else

  {

  strsql = "select QuestionId,ChapterId,QuestionTypeId,Point,Degree,Fraction,QuestionContent,cast(Answer1 as nvarchar(4000)) + cast(Answer2 as nvarchar(4000)) + cast(Answer3 as nvarchar(4000)) + cast(Answer4 as nvarchar(4000)) + cast(Answer5 as nvarchar(4000)) + cast(Answer6 as nvarchar(4000)) AS CorrectAnswer,IsValid from " + strTableName + " where ChapterId=@chapterid and QuestionTypeId=@questiontypeid";

  }

  //strsql = "select * from " + strTableName + " where ChapterId=@chapterid and QuestionTypeId=@questiontypeid";

  SqlParameter[] paras = new SqlParameter[]{

  new SqlParameter("@chapterid",strChapterName),

  new SqlParameter("@questiontypeid",strQuestionTypeName)

  };

  dt = sqlHelper.ExecuteQuery(strsql,paras,CommandType.Text);

  return dt;

  }

  catch

  {

  throw new Exception("从动态生成的数据库表中获取QuestionId,ChapterId,QuestionTypeId,Point失败(不包括难度等级)");

  }

  finally

  {

  sqlHelper.Close();

  }

  }

  #endregion

  其中使用cast函数的strSql语句所起到的作用就是将多个字段合并成一个新字段。另外需要注意的是strSql语句中的 “ + ” 号,如果需要合并的字段的内容是Text类型的,是不支持该符号的,这时我们需要将其转换成nvarchar类型。到此多列合并问题完美解决。