以下是學習筆記:
一,添加新學員
1,后台部分:在DAL---StudentService中添加代碼
/// <summary>
/// 判斷當前身份證號是否已經存在
/// </summary>
/// <param name="studentIdNo"></param>
/// <returns></returns>
public bool IsIdNoExisted(string studentIdNo)
{
string sql = "select count(*) from Students where StudentIdNo={0}";
sql = string.Format(sql, studentIdNo);
int result = Convert.ToInt32(SQLHelper.GetSingleResult(sql));
if (result == 1) return true;
else return false;
}
/// <summary>
/// 添加學員
/// </summary>
/// <param name="objStudent"></param>
/// <returns></returns>
public int AddStudent(Student objStudent)
{
//【1】編寫SQL語句
StringBuilder sqlBuilder = new StringBuilder();//如果字符串比較長,可以用StringBuilder
sqlBuilder.Append("insert into Students(StudentName,Gender,Birthday,StudentIdNo,Age,PhoneNumber,StudentAddress,CardNo,ClassId)");
sqlBuilder.Append(" values('{0}','{1}','{2}',{3},{4},'{5}','{6}','{7}',{8})");
//【2】解析對象
string sql = string.Format(sqlBuilder.ToString(),
objStudent.StudentName, objStudent.Gender, objStudent.Birthday.ToString("yyyy-MM-dd"),
objStudent.StudentIdNo, objStudent.Age, objStudent.PhoneNumber,
objStudent.StudentAddress, objStudent.CardNo, objStudent.ClassId);
//【3】提交到數據庫
try
{
return SQLHelper.Update(sql);
}
catch (SqlException ex)
{
throw new Exception("數據庫操作出現異常!具體信息:" + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
}
2,UI部分

確認添加的按鈕事件
private void btnAdd_Click(object sender, EventArgs e)
{
#region 驗證數據
if (this.txtStudentName.Text.Trim().Length == 0)
{
MessageBox.Show("學生姓名不能為空!", "提示信息");
this.txtStudentName.Focus();
return;
}
if (this.txtCardNo.Text.Trim().Length == 0)
{
MessageBox.Show("考勤卡號不能為空!", "提示信息");
this.txtCardNo.Focus();
return;
}
//驗證性別
if (!this.rdoFemale.Checked && !this.rdoMale.Checked)
{
MessageBox.Show("請選擇學生性別!", "提示信息");
return;
}
//驗證班級
if (this.cboClassName.SelectedIndex == -1)
{
MessageBox.Show("請選擇班級!", "提示信息");
return;
}
//驗證身份證號是否符合要求
if (!Common.DataValidate.IsIdentityCard(this.txtStudentIdNo.Text.Trim()))
{
MessageBox.Show("身份證號不符合要求!", "驗證提示");
this.txtStudentIdNo.Focus();
return;
}
//驗證身份證號是否重復
if (objStudentService.IsIdNoExisted(this.txtStudentIdNo.Text.Trim()))
{
MessageBox.Show("身份證號不能和現有學員身份證號重復!", "驗證提示");
this.txtStudentIdNo.Focus();
this.txtStudentIdNo.SelectAll();
return;
}
//驗證身份證號是否和出生日期相吻合
string month = string.Empty;
string day = string.Empty;
if (Convert.ToDateTime(this.dtpBirthday.Text).Month < 10)
month = "0" + Convert.ToDateTime(this.dtpBirthday.Text).Month;
else
month = Convert.ToDateTime(this.dtpBirthday.Text).Month.ToString();
if (Convert.ToDateTime(this.dtpBirthday.Text).Day < 10)
day = "0" + Convert.ToDateTime(this.dtpBirthday.Text).Day;
else
day = Convert.ToDateTime(this.dtpBirthday.Text).Day.ToString();
string birthday = Convert.ToDateTime(this.dtpBirthday.Text).Year.ToString() + month + day;
if (!this.txtStudentIdNo.Text.Trim().Contains(birthday))
{
MessageBox.Show("身份證號和出生日期不匹配!", "驗證提示");
this.txtStudentIdNo.Focus();
this.txtStudentIdNo.SelectAll();
return;
}
//驗證出生日期
int age = DateTime.Now.Year - Convert.ToDateTime(this.dtpBirthday.Text).Year;
if (age < 18)
{
MessageBox.Show("學生年齡不能小於18歲!", "驗證提示");
return;
}
#endregion
#region 封裝學生對象
Student objStudent = new Student()
{
StudentName = this.txtStudentName.Text.Trim(),
Gender = this.rdoMale.Checked ? "男" : "女",
Birthday = Convert.ToDateTime(this.dtpBirthday.Text),
StudentIdNo = this.txtStudentIdNo.Text.Trim(),
PhoneNumber = this.txtPhoneNumber.Text.Trim(),
StudentAddress = this.txtAddress.Text.Trim(),
CardNo = this.txtCardNo.Text.Trim(),
ClassId = Convert.ToInt32(this.cboClassName.SelectedValue),//獲取選擇班級對應的ClassId
Age = DateTime.Now.Year - Convert.ToDateTime(this.dtpBirthday.Text).Year
};
#endregion
#region 調用后台數據訪問方法添加對象
try
{
if (objStudentService.AddStudent(objStudent) == 1)
{
DialogResult result = MessageBox.Show("新學員添加成功!是否繼續添加?", "提示信息", MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)//清空用戶的輸入
{
this.cboClassName.SelectedIndex = -1;
this.rdoFemale.Checked = false;
this.rdoMale.Checked = false;
//清除文本框
foreach (Control item in this.Controls)
{
if (item is TextBox)
item.Text = "";
}
this.txtStudentName.Focus();
}
}
else
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
二,學員信息查詢
1,Models中添加2個實體類 :Models--Students 和擴展實體類Models--Ext-StudentExt
Students:
namespace Models
{
/// <summary>
/// 學員實體類
/// </summary>
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public string Gender { get; set; }
public DateTime Birthday{ get; set; }
//將數據庫中的18位整數轉換成字符串
public string StudentIdNo { get; set; }
public int Age { get; set; }
public string PhoneNumber { get; set; }
public string StudentAddress { get; set; }
public string CardNo { get; set; }
public int ClassId { get; set; }
}
}
StudentExt:
namespace Models
{
/// <summary>
/// 學員信息擴展實體
/// </summary>
public class StudentExt : Student
{
public string ClassName { get; set; }
public int CSharp { get; set; }
public int SQLServerDB { get; set; }
}
}
2,在DAL--StudentService學員信息數訪問類添加查詢方法
#region 查詢學員【根據班級、學號、卡號】
/// <summary>
/// 根據班級名稱查詢學員信息
/// </summary>
/// <param name="className"></param>
/// <returns></returns>
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;
}
/// <summary>
///根據學號查詢學員對象
/// </summary>
/// <param name="studentId"></param>
/// <returns></returns>
public StudentExt GetStudentById(string studentId)
{
string sql = "select StudentId,StudentName,Gender,Birthday,ClassName,StudentIdNo,PhoneNumber,StudentAddress,CardNo from Students";
sql += " inner join StudentClass on Students.ClassId=StudentClass.ClassId";
sql += " where StudentId=" + studentId;
SqlDataReader objReader = SQLHelper.GetReader(sql);
StudentExt objStudent = null;
if (objReader.Read())
{
objStudent = new StudentExt()
{
StudentId = Convert.ToInt32(objReader["StudentId"]),
StudentName = objReader["StudentName"].ToString(),
Gender = objReader["Gender"].ToString(),
Birthday = Convert.ToDateTime(objReader["Birthday"]),
ClassName = objReader["ClassName"].ToString(),
CardNo = objReader["CardNo"].ToString(),
StudentIdNo = objReader["StudentIdNo"].ToString(),
PhoneNumber = objReader["PhoneNumber"].ToString(),
StudentAddress = objReader["StudentAddress"].ToString()
};
}
objReader.Close();
return objStudent;
}
/// <summary>
/// 根據卡號查詢學生信息(請思考如何將上面的方法合並,像下面的方法這么簡單)
/// </summary>
/// <param name="CardNo"></param>
/// <returns></returns>
public StudentExt GetStudentByCardNo(string CardNo)
{
string whereSql = string.Format(" where CardNo='{0}'", CardNo);
return this.GetStudent(whereSql);
}
private StudentExt GetStudent(string whereSql)
{
string sql = "select StudentId,StudentName,Gender,Birthday,ClassName,";
sql += "StudentIdNo,PhoneNumber,StudentAddress,CardNo from Students";
sql += " inner join StudentClass on Students.ClassId=StudentClass.ClassId ";
sql += whereSql;
SqlDataReader objReader = SQLHelper.GetReader(sql);
StudentExt objStudent = null;
if (objReader.Read())
{
objStudent = new StudentExt()
{
StudentId = Convert.ToInt32(objReader["StudentId"]),
StudentName = objReader["StudentName"].ToString(),
Gender = objReader["Gender"].ToString(),
Birthday = Convert.ToDateTime(objReader["Birthday"]),
ClassName = objReader["ClassName"].ToString(),
CardNo = objReader["CardNo"].ToString(),
StudentIdNo = objReader["StudentIdNo"].ToString(),
PhoneNumber = objReader["PhoneNumber"].ToString(),
StudentAddress = objReader["StudentAddress"].ToString()
};
}
objReader.Close();
return objStudent;
}
#endregion
3,UI部分

查詢按鈕事件代碼:
//按照班級查詢
private void btnQuery_Click(object sender, EventArgs e)
{
if (this.cboClass.SelectedIndex == -1)
{
MessageBox.Show("請選擇班級!", "提示信息");
return;
}
this.dgvStudentList.AutoGenerateColumns = false;//DataGridView中設置不顯示未封裝的屬性
//執行查詢
this.dgvStudentList.DataSource = objStuService.GetStudentByClass(this.cboClass.Text);
}
//根據學號查詢
private void btnQueryById_Click(object sender, EventArgs e)
{
if (this.txtStudentId.Text.Trim().Length == 0)
{
MessageBox.Show("請輸入學號!", "提示信息");
this.txtStudentId.Focus();
return;
}
//進一步驗證學號必須是數字(請使用正則表達式...)
//執行查詢
StudentExt objStudent = objStuService.GetStudentById(this.txtStudentId.Text.Trim());
if (objStudent == null)
{
MessageBox.Show("學員信息不存在!", "提示信息");
this.txtStudentId.Focus();
}
else
{
//在學員詳細信息窗體顯示
FrmStudentInfo objFrmStuInfo = new FrmStudentInfo(objStudent);
objFrmStuInfo.Show();
}
}
學員信息顯示:

學員信息顯示代碼:
public partial class FrmStudentInfo : Form
{
public FrmStudentInfo()
{
InitializeComponent();
}
public FrmStudentInfo(StudentExt objStudent)
: this()//調用默認的構造方法
{
//顯示學員信息
this.lblStudentName.Text = objStudent.StudentName;
this.lblStudentIdNo.Text = objStudent.StudentIdNo;
this.lblPhoneNumber .Text = objStudent.PhoneNumber;
this.lblBirthday.Text = objStudent.Birthday.ToShortDateString();
this.lblAddress.Text = objStudent.StudentAddress;
this.lblGender.Text = objStudent.Gender;
this.lblClass.Text = objStudent.ClassName;
this.lblCardNo.Text = objStudent.CardNo;
}
//關閉
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
三,學員信息修改
1,后台代碼:
在DAL--StudentService中添加修改學員對象的方法
#region 修改學員對象
/// <summary>
/// 修改學員時判斷身份證號是否和其他學員重復
/// </summary>
/// <param name="studentIdNo"></param>
/// <param name="studentId"></param>
/// <returns></returns>
public bool IsIdNoExisted(string studentIdNo, string studentId)
{
string sql = "select count(*) from Students where StudentIdNo={0} and StudentId<>{1}";
sql = string.Format(sql, studentIdNo, studentId);
int result = Convert.ToInt32(SQLHelper.GetSingleResult(sql));
if (result == 1) return true;
else return false;
}
/// <summary>
/// 修改學員對象
/// </summary>
/// <param name="objStudent"></param>
/// <returns></returns>
public int ModifyStudent(Student objStudent)
{
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.Append("Update Students set StudentName='{0}',Gender='{1}',Birthday='{2}',");
sqlBuilder.Append("StudentIdNo={3},Age={4},PhoneNumber='{5}',StudentAddress='{6}',CardNo='{7}',ClassId={8}");
sqlBuilder.Append(" where StudentId={9}");//注意where前面有空格
//解析對象
string sql = string.Format(sqlBuilder.ToString(),
objStudent.StudentName, objStudent.Gender, objStudent.Birthday,
objStudent.StudentIdNo, objStudent.Age, objStudent.PhoneNumber,
objStudent.StudentAddress, objStudent.CardNo, objStudent.ClassId, objStudent.StudentId);
try
{
return SQLHelper.Update(sql);
}
catch (SqlException ex)
{
throw new Exception("數據庫操作出現異常!具體信息:" + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
2,前端UI點擊修改代碼的事件代碼

修改的代碼:
//修改學員對象
private void btnEidt_Click(object sender, EventArgs e)
{
if (this.dgvStudentList.RowCount == 0)
{
MessageBox.Show("沒有任何要修改的學信息!", "提示信息");
return;
}
if (this.dgvStudentList.CurrentRow == null)//判斷當前行
{
MessageBox.Show("請選中要修改的學員信息!", "提示信息");
return;
}
//獲取學號
string studentId = this.dgvStudentList.CurrentRow.Cells["StudentId"].Value.ToString();
//獲取要修改的學員詳細信息
StudentExt objStudent = objStuService.GetStudentById(studentId);
//顯示要修改的學員信息窗口
FrmEditStudent objEditStudent = new FrmEditStudent(objStudent);
DialogResult result = objEditStudent.ShowDialog();
//判斷修改是否成
if (result == DialogResult.OK)
{
btnQuery_Click(null, null);//同步刷新修改的信息(適合查詢數據量小的情況)
}
}
3,修改學員信息的代碼
通過構造函數把學員信息對象傳過來

提交修改的代碼
//提交修改
private void btnModify_Click(object sender, EventArgs e)
{
#region 驗證信息
if (this.txtStudentName.Text.Trim().Length == 0)
{
MessageBox.Show("學生姓名不能為空!", "提示信息");
this.txtStudentName.Focus();
return;
}
//驗證性別
if (!this.rdoFemale.Checked && !this.rdoMale.Checked)
{
MessageBox.Show("請選擇學生性別!", "提示信息");
return;
}
//驗證班級
if (this.cboClassName.SelectedIndex == -1)
{
MessageBox.Show("請選擇班級!", "提示信息");
return;
}
//驗證身份證號是否符合要求
if (!Common.DataValidate.IsIdentityCard(this.txtStudentIdNo.Text.Trim()))
{
MessageBox.Show("身份證號不符合要求!", "驗證提示");
this.txtStudentIdNo.Focus();
return;
}
//驗證身份證號是否重復
if (objStudentService.IsIdNoExisted(this.txtStudentIdNo.Text.Trim(), this.txtStudentId.Text.Trim()))
{
MessageBox.Show("身份證號不能和現有學員身份證號重復!", "驗證提示");
this.txtStudentIdNo.Focus();
this.txtStudentIdNo.SelectAll();
return;
}
//驗證身份證號是否和出生日期相吻合
string month = string.Empty;
string day = string.Empty;
if (Convert.ToDateTime(this.dtpBirthday.Text).Month < 10)
month = "0" + Convert.ToDateTime(this.dtpBirthday.Text).Month;
if (Convert.ToDateTime(this.dtpBirthday.Text).Day < 10)
day = "0" + Convert.ToDateTime(this.dtpBirthday.Text).Day;
string birthday = Convert.ToDateTime(this.dtpBirthday.Text).Year.ToString() + month + day;
if (!this.txtStudentIdNo.Text.Trim().Contains(birthday))
{
MessageBox.Show("身份證號和出生日期不匹配!", "驗證提示");
this.txtStudentIdNo.Focus();
this.txtStudentIdNo.SelectAll();
return;
}
//驗證出生日期
int age = DateTime.Now.Year - Convert.ToDateTime(this.dtpBirthday.Text).Year;
if (age < 18)
{
MessageBox.Show("學生年齡不能小於18歲!", "驗證提示");
return;
}
#endregion
#region 封裝學生對象
Student objStudent = new Student()
{
StudentId = Convert.ToInt32(this.txtStudentId.Text.Trim()),
StudentName = this.txtStudentName.Text.Trim(),
Gender = this.rdoMale.Checked ? "男" : "女",
Birthday = Convert.ToDateTime(this.dtpBirthday.Text),
StudentIdNo = this.txtStudentIdNo.Text.Trim(),
PhoneNumber = this.txtPhoneNumber.Text.Trim(),
StudentAddress = this.txtAddress.Text.Trim(),
CardNo = this.txtCardNo.Text.Trim(),
ClassId = Convert.ToInt32(this.cboClassName.SelectedValue),//獲取選擇班級對應的ClassId
Age = DateTime.Now.Year - Convert.ToDateTime(this.dtpBirthday.Text).Year
};
#endregion
#region 提交修改
try
{
if (objStudentService.ModifyStudent(objStudent) == 1)
{
MessageBox.Show("學員信息修改成功!", "提示信息");
this.DialogResult = DialogResult.OK;//返回修改成功的信息
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
4,優化用戶體驗,雙擊顯示學員信息
//雙擊選中的學員對象並顯示詳細信息
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);
}
}
5,優化用戶體驗,右鍵就可以修改(查看)學員信息,效果如下:

1,添加contextMenuStrip控件
,2,設置DataGridView的ContextMenuStrip

3,設置ContextMenuStrip的事件代碼:
//右鍵菜單的事件
private void tsmiModifyStu_Click(object sender, EventArgs e)
{
btnEidt_Click(null, null);//修改學員對象按鈕的事件
}
四,刪除學員信息
1,后台代碼
在DAL--StudentService中添加刪除學員對象的方法
#region 刪除學員對象
public int DeleteStudentById(string studentId)
{
string sql = "delete from Students where StudentId=" + studentId;
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 ex;
}
}
#endregion
2,前端UI

刪除按鈕的事件代碼:
//刪除學員對象
private void btnDel_Click(object sender, EventArgs e)
{
if (this.dgvStudentList.RowCount == 0)
{
MessageBox.Show("沒有任何要刪除的學信息!", "提示信息");
return;
}
if (this.dgvStudentList.CurrentRow == null)
{
MessageBox.Show("請選中要刪除的學員信息!", "提示信息");
return;
}
//刪除確認
string studentName = this.dgvStudentList.CurrentRow.Cells["StudentName"].Value.ToString();
DialogResult result = MessageBox.Show("確認要刪除學員 [" + studentName + "] 嗎?", "刪除詢問", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.Cancel) return;
//獲取學號並刪除
string studentId = this.dgvStudentList.CurrentRow.Cells["StudentId"].Value.ToString();
try
{
if (objStuService.DeleteStudentById(studentId) == 1)
{
btnQuery_Click(null, null);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示信息");
}
}
