按照班级查询学员对象

文章目录

    • 1 按照班级查询学员对象后台访问方法实现
    • 2 UI的实现
      • 2.1 FrmMain中创建学员管理窗体
      • 2.2 学员管理窗体中查询UI实现

1 按照班级查询学员对象后台访问方法实现

/// 
/// 根据班级名称查询学员信息
/// 
/// 
/// 
public List<StudentExt> GetStudentByClass(string className)
{
    string sql = "select StudentName,StudentId,Gender,Birthday,ClassName from Students";
    sql += " inner join StudentClass on Students.ClassId=StudentClass.ClassId";
    sql += " where ClassName='{0}'";
    sql = string.Format(sql, className);
    SqlDataReader objReader = SQLHelper.GetReader(sql);
    List<StudentExt> list = new List<StudentExt>();
    while (objReader.Read())
    {
        list.Add(new StudentExt()
            {
                StudentId = Convert.ToInt32(objReader["StudentId"]),
                StudentName = objReader["StudentName"].ToString(),
                Gender = objReader["Gender"].ToString(),
                Birthday = Convert.ToDateTime(objReader["Birthday"]),
                ClassName = objReader["ClassName"].ToString()
            });
    }
    objReader.Close();
    return list;

}

2 UI的实现

2.1 FrmMain中创建学员管理窗体

按照班级查询学员对象_第1张图片
添加创建窗体的代码:

//学员管理
public static FrmStudentManage objFrmStuManage = null;
private void tsmiManageStudent_Click(object sender, EventArgs e)
{
    if (objFrmStuManage == null)
    {
        objFrmStuManage = new FrmStudentManage();
        objFrmStuManage.Show();
    }
    else
    {
        objFrmStuManage.Activate();
        objFrmStuManage.WindowState = FormWindowState.Normal;
    }
}

学员管理窗体关闭事件中将objFrmStuManage 设置为null:

private void FrmSearchStudent_FormClosed(object sender, FormClosedEventArgs e)
{
    FrmMain.objFrmStuManage = null;
}

2.2 学员管理窗体中查询UI实现

按照班级查询学员对象_第2张图片

private StudentClassService objClassService = new StudentClassService();
private StudentService objStuService = new StudentService();
public FrmStudentManage()
{
    InitializeComponent();
    //初始化班级下拉框
    this.cboClass.DataSource = objClassService.GetAllClasses();
    this.cboClass.DisplayMember = "ClassName";
    this.cboClass.ValueMember = "ClassId";
    this.cboClass.SelectedIndex = -1;//默认不选中
}

//按照班级查询
private void btnQuery_Click(object sender, EventArgs e)
{
    if (this.cboClass.SelectedIndex == -1)
    {
        MessageBox.Show("请选择班级!", "提示信息");
        return;
    }
    this.dgvStudentList.AutoGenerateColumns = false;//不显示未封装的属性
    //执行查询
    this.dgvStudentList.DataSource = objStuService.GetStudentByClass(this.cboClass.Text);
}

优化用户体验,双击表格指定列,显示对应的学员详细信息:

//双击选中的学员对象并显示详细信息
private void dgvStudentList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (this.dgvStudentList.CurrentRow != null)
    {
        string studentId = this.dgvStudentList.CurrentRow.Cells["StudentId"].Value.ToString();
        this.txtStudentId.Text = studentId;
        btnQueryById_Click(null, null);
    }
}

你可能感兴趣的:(C#)