private void button4_Click(object sender, EventArgs e) { this.dataGridView1.DataSource = null; if (this.cmbClass.SelectedValue == null || this.cmbSubjects.SelectedValue == null) { MessageBox.Show("你还没选中专业或学科?"); return; } //创建某专业表dt作为datagridview的数据源 DataTable dt = new DataTable(); //为dt表创建数据列 DataColumn cnum = new DataColumn("学号", typeof(string)); //创建学号列 DataColumn cname = new DataColumn("姓名", typeof(string)); //创建姓名列 dt.Columns.Add(cnum); dt.Columns.Add(cname);//将此列添加到表dt中 //遍历学科列表,将每个学科构建成表中的列,列名为学科名称 for (int i = 0; i < cmbSubjects.Items.Count; i++) { string subname = ((DataRowView)this.cmbSubjects.Items[i])["Subjects_Name"].ToString(); DataColumn cgrade = new DataColumn(subname, typeof(int)); cgrade.DefaultValue = 0;//默认值为0 dt.Columns.Add(cgrade); } DataColumn csum = new DataColumn("总分", typeof(int)); dt.Columns.Add(csum); //为dt表添加数据行 //2.1根据专业编号选出该专业所有学生所有信息的成绩形成信息表 ClassesModel clamodel = new ClassesModel(); StudentsBLL student = new StudentsBLL(); clamodel.Classes_Speciality = this.cmbSpeciality.SelectedValue.ToString(); DataTable stu = student.GetStudentsBySpec(clamodel);//查询选中专业的所有学生形成学生表 //2.2根据专业编号选出该班级所有学生所有科目的成绩形成成绩表 SpecialityModel spemodel = new SpecialityModel(); spemodel.Speciality_ID = this.cmbSpeciality.SelectedValue.ToString(); DataTable exam = examin.GetAllGradeBySpeciality(spemodel); //遍历学生表中所有行,将每个学生构造成一个和自定义的ì?dt表具有相同结构的数据行 for (int i = 0; i < stu.Rows.Count; i++) { DataRow row = dt.NewRow(); row["学号"] = stu.Rows[i]["StudentNum"]; //初始化一个表具有相同结构的数据行 row["姓名"] = stu.Rows[i]["Student_Name"]; //从学生表第i行取出学号列赋dt表学号? //从结果集表中再次查询单个成绩并返回数据行集合 DataRow[] rows = exam.Select("StudentID=" + stu.Rows[i]["Student_ID"]); int total = 0; //总分 string name; //科目的列名 int score = 0; for (int j = 0; j < rows.Length; j++) { //获取科目名称 name = ((DataRowView)this.cmbSubjects.Items[j])["Subjects_Name"].ToString(); score = Convert.ToInt32(rows[j]["ExamScore"]); //把第i个学生的第i个成绩取出 row[name] = score; //填充成绩到表中 total += score; //累加总分 } row["总分"] = total; dt.Rows.Add(row);//将构造好的行添加到行集合 } //3创建数据表的视图进行排序 DataView view = dt.DefaultView; if (this.checkBox1.Checked) { view.Sort = "总分 desc"; } else { view.Sort = "总分 asc"; } this.dataGridView1.DataSource = dt; }