1.科目管理
private CourseService courseService = new CourseService();
public ListCourseForm()
{
InitializeComponent();
}
//查询所有课程信息
private void btnListCourse_Click(object sender, EventArgs e)
{
List<Course> list = courseService.GetCourseList(); //所有课程信息
this.dgvListCourse.AutoGenerateColumns = false;
this.dgvListCourse.DataSource = list;
}
//新建课程
private void btnAddCourse_Click(object sender, EventArgs e)
{
AddCourseForm addCourseForm = new AddCourseForm();
DialogResult result = addCourseForm.ShowDialog();
if (result == DialogResult.OK)
{
btnListCourse_Click(null, null);
}
}
//删除科目
private void btnDelCourse_Click(object sender, EventArgs e)
{
//判断用户是否选中
if (this.dgvListCourse.RowCount == 0 || this.dgvListCourse.CurrentRow == null)
{
MessageBox.Show("没有要修改的信息!", "信息提示");
return;
}
if (this.dgvListCourse.CurrentRow.Cells["CourseId"].Value == null)
{
MessageBox.Show("没有要删除的信息!", "信息提示");
return;
}
//删除确认
DialogResult result = MessageBox.Show("确认要删除吗?", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
{
return;
}
//获取要删除的courseId
string courseId = this.dgvListCourse.CurrentRow.Cells["CourseId"].Value.ToString();
//根据科目Id删除
try
{
if (courseService.DeleteClassById(courseId) == 1)
{
MessageBox.Show("删除成功!", "信息提示");
btnListCourse_Click(null, null);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "删除信息");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
查询科目:
/// <summary>
/// 查询所有课程信息
/// </summary>
/// <returns></returns>
public List<Course> GetCourseList()
{
List<Course> list = new List<Course>();
string sql = "select CourseId,CourseName from Course";
SqlDataReader dataReader = SQLHelper.GetReader(sql);
while (dataReader.Read())
{
Course course = new Course();
course.CourseId = Convert.ToInt32(dataReader["CourseId"]);
course.CourseName = dataReader["CourseName"].ToString();
list.Add(course);
}
dataReader.Close();
return list;
}
新建科目:
//添加课程信息
public int AddCourse(Course course)
{
string sql = "insert into Course (CourseName) values('{0}')";
sql = string.Format(sql, course.CourseName);
try
{
return SQLHelper.Update(sql);
}
catch (Exception ex)
{
throw new Exception("添加课程信息出错!" + ex.Message); ;
}
}
删除科目:
如果一个科目已经被学生添加了成绩,那么该科目不可以删除。科目的名称不能更改,所以灭有设计编辑按钮。
//删除课程信息
public int DeleteClassById(string courseId)
{
string sql = "delete from Course where CourseId=" + courseId;
try
{
return SQLHelper.Update(sql);
}
catch (SqlException ex)
{
if (ex.Number == 547)
{
throw new Exception("当课程以包含成绩信息,不能删除!");
}
else
{
throw new Exception("删除信息错误:" + ex.Message);
}
}
catch (Exception ex)
{
throw new Exception("删除课程信息错误!" + ex.Message);
}
}