该程序实现数据导入、添加、修改、删除。
并显示信息明细,具体包括:学号、姓名、出生日期、性别、电话、邮箱、家庭住址及学生照片信息等。
功能界面如图所示:
程序如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace StudentManage
{
public partial class frmMain : Form
{
private string fileName = string.Empty; //定义变量保存读取文件路径的变量 (全局变量), 默认情况下加载时是空的,等同于 = “”;
private string photoName = string.Empty; //记录上传图片时候的文件路径;
private List<string> objListStudent = new List<string>(); //定义List存储读取到的学生信息;
private List<string> objListQuery = new List<string>(); //经过查询满足条件的学生信息;
private int actionFlag = 0; //通过actionFlag值判断是添加还是修改,cationFlag=1(添加), cationFlag=2(修改);
public frmMain()
{
InitializeComponent();
//禁用明细区域,仅显示明细,而不能手动修改;
gboxStudentDetail.Enabled = false;
}
//运行过程--业务逻辑;
//数据的导入和展示:选择文件-》导入到DataGridView中-->展示选择学生明细-->选择学生不同,明细随之变化;
/*
图片: 选择图片-->通过“选择按钮”
保存图片-》通过“提交”将图片另存到一个统一的相对路径;
读取图片--》选择一个学员的时候,按照存储的路径展示相应的图片;
*/
//流程:点击关闭--》询问是否保存数据,如果需要,保存,不需要直接退出;
// 关于保存:添加---》添加的放到最后; 修改:如何定位到修改的学生信息???、
//换个思维: objListStudent包含了所有数据,在保存前将现有文件清空,把objListStudent数据写入到文件;
//控件事件;
private void button1_Click(object sender, EventArgs e) //导入数据并显示;
{
//【1】选择文件
OpenFileDialog openfile = new OpenFileDialog();
openfile.Filter = "CSV文件(*.csv)|*.csv|TXT文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //文件类型;
if (openfile.ShowDialog() == DialogResult.OK) //选择打开按钮
{
fileName = openfile.FileName; //将选择的文件名完整路径赋给全局变量fileName;
}
//【2】把文件的数据读取到List中;
//为防止读取的时候有些文件无法正常读取,如文件已被删除,正在处理等,加一个异常处理;
try
{
//读取文件;
objListStudent = ReadFileToList(fileName);
}
catch (Exception ex)
{
MessageBox.Show("读取文件出现错误,具体错误如下:" + ex.Message, "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//【3】把List中的数据展示在DataGridView中;
LoadDataToDataGrid(objListStudent);
//【4】把DataGridView的第一行数据的明细展示在明细groupBox中;
string currentSNo = dgvStudent.Rows[0].Cells[0].Value.ToString(); //通过表格读取第一行第一列,即为学号;
//string currentDetail = GetStudentBySNO(currentSNo);
string[] currentDetail = GetStudentBySNO(currentSNo).Split(','); //获取当前学号学生信息,并以逗号分隔;
//把当前学生展示在明细中
LoadDataToDetail(currentDetail[0], currentDetail[1],currentDetail[2],currentDetail[3],currentDetail[4],
currentDetail[5], currentDetail[6],currentDetail[7]);
}
private void dgvStudent_SelectionChanged(object sender, EventArgs e)//明细数据随着表格中选择的行为发生变化;
{
if (dgvStudent.CurrentRow.Selected == false) return;
else
{
string currentSNo = dgvStudent.CurrentRow.Cells[0].Value.ToString(); //读取当前行的学号;
string[] currentDetail = GetStudentBySNO(currentSNo).Split(',');
LoadDataToDetail(currentDetail[0], currentDetail[1], currentDetail[2], currentDetail[3], currentDetail[4],
currentDetail[5], currentDetail[6], currentDetail[7]);
}
}
private void txtQuerySNO_TextChanged(object sender, EventArgs e) //根据学号查询;
{
objListQuery.Clear(); //清空存储查询结果的List;
//查询当前哪些满足条件,并添加到QueryList中;
foreach(string item in objListStudent)
{
if (item.StartsWith(txtQuerySNO.Text))
//如果是查询包含某些数字的学号,可改为: item.Contains
objListQuery.Add(item);
}
//清空当前表格数据
dgvStudent.Rows.Clear();
//把查询结果展示在DataGridView中
LoadDataToDataGrid(objListQuery);
}
private void txtQueryMobile_TextChanged(object sender, EventArgs e) //根据手机号码查询
{
objListQuery.Clear(); //清空存储查询结果的List;
//查询当前哪些满足条件,并添加到QueryList中;
foreach (string item in objListStudent)
{
if (item.Contains(txtQueryMobile.Text)) //是否包含查询电话;
objListQuery.Add(item);
}
//清空当前表格数据
dgvStudent.Rows.Clear();
//把查询结果展示在DataGridView中
LoadDataToDataGrid(objListQuery);
}
private void txtQueryName_TextChanged(object sender, EventArgs e)//根据姓名查询
{
objListQuery.Clear(); //清空存储查询结果的List;
//查询当前哪些满足条件,并添加到QueryList中;
foreach (string item in objListStudent)
{
if (item.Contains(txtQueryName.Text)) //是否包含查询名字;
objListQuery.Add(item);
}
//清空当前表格数据
dgvStudent.Rows.Clear();
//把查询结果展示在DataGridView中
LoadDataToDataGrid(objListQuery);
}
private void btnAdd_Click(object sender, EventArgs e)//添加学生信息;
{
//添加过程: 点击添加按钮-->数据输入-->判断数据是否有效-->提交;
//控制启用和禁用;
DisableButton();
//让明细窗体中文本框清空
txtNO.Text = string.Empty;
txtName.Text = string.Empty;
txtMobile.Text = string.Empty;
txtHomeAddress.Text = string .Empty;
txtEmali.Text = string.Empty;
dtpBirthday.Text = DateTime.Now.ToString(); //日期显示为今天;
rbMale.Checked = true; //默认为男生;
pbCurrentPhoto.BackgroundImage = null; //照片默认为空;
//让学号的文本框获得焦点
txtNO.Focus();
//修改actionFlag
actionFlag = 1;
}
private void btnUpdate_Click(object sender, EventArgs e) //修改学生信息;
{
//修改==删除旧的+添加新的 并到相同位置;
//准备
//控制按钮
DisableButton();
//学号不允许修改
txtNO.Enabled = false;
//让学生姓名文本框获得焦点
txtName.Focus();
//修改actionFlag
actionFlag = 2;
}
private void btnDelete_Click(object sender, EventArgs e)//删除学生信息;
{
if(dgvStudent.CurrentRow.Selected == false)
{
MessageBox.Show("删除前必须要选择某一行!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
string info= "您确定要删除学生 【学号:"+dgvStudent.CurrentRow.Cells[0].Value.ToString()+"姓名:"+
dgvStudent.CurrentRow.Cells[1].Value.ToString()+"】信息吗??";
DialogResult result= MessageBox.Show(info,"系统提示",MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
string currentStudent = GetStudentBySNO(dgvStudent.CurrentRow.Cells[0].Value.ToString());
foreach (string item in objListStudent)
{
if (item.Equals(currentStudent))
{
objListStudent.Remove(item); //删除;
MessageBox.Show("学生信息删除成功!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
//把添加后的List展示
dgvStudent.Rows.Clear();
LoadDataToDataGrid(objListStudent);
break;
}
}
}
else return;
}
}
private void btnCommit_Click(object sender, EventArgs e)//提交添加和修改的操作;
{
if (!ValiDate()) return; //如果返回值为false,即不满足条件直接返回
else
{
//图片另存为: 如何保证另存为图片名称不重复(日期+时间+随机号)20201022+185020+两位随机值
string photoPath = DateTime.Now.ToString("yyyyMMddHHmmss"); //年月日时分秒
Random objRandom = new Random();
photoPath+=objRandom.Next(0, 100).ToString("00"); //生成两位随机数,[0,100),并转化为两位数;
//再加上图像的后缀,这就需要先读取到之前的,定义一个全局变量记录上传图片时候的文件路径
photoPath += photoName.Substring(photoName.Length- 4,4); //取最后四位
photoPath = ".\\image\\" + photoPath; //保存在了相对路径 StudentManage/bin/Debug/image 中,即与生成的可执行文件在一个文件夹下;
//存储
Bitmap objBitmap = new Bitmap(pbCurrentPhoto.BackgroundImage); //利用现有图片完成初始化
objBitmap.Save(photoPath, pbCurrentPhoto.BackgroundImage.RawFormat); //保存
objBitmap.Dispose();
//组合数据,准备添加到List中
string sno = txtNO.Text.Trim();
string sname = txtName.Text.Trim();
string sex = rbMale.Checked == true ? "男" : "女";
string birthday = dtpBirthday.Text;
string mobile = txtMobile.Text;
string email = txtEmali.Text;
string homeAddress = txtHomeAddress.Text;
// string photo = string.Empty; //照片为空
string photo = photoPath; //将图片相对路径存储;
string currentStudent = sno + ',' + sname + ',' + sex + ',' + birthday + ',' + mobile + ','
+ email + ',' + homeAddress + ',' + photo;
switch (actionFlag)
{
case 1: //添加;
//把数据添加到List;
objListStudent.Add(currentStudent);
//把添加后的List展示
dgvStudent.Rows.Clear();
LoadDataToDataGrid(objListStudent);
//显示添加成功
MessageBox.Show("学生信息添加成功!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
//控制按钮
EnableButton();
break;
case 2: //修改;
for (int i = 0; i < objListStudent.Count;i++ ) //在所有列表中查询,用for循环是因为其能记录到位置,
{
if (objListStudent[i].StartsWith(sno )) //查到第i个以该学号开头
{
//删除原有的
objListStudent.RemoveAt(i);
//插入添加的
objListStudent.Insert(i, currentStudent);
break;
}
}
//把添加后的List展示
dgvStudent.Rows.Clear();
LoadDataToDataGrid(objListStudent);
//提示修改完成
MessageBox.Show("学生信息修改成功!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
//控制按钮
EnableButton();
//学号文本框启用
txtNO.Enabled = true;
break;
default:
break;
}
}
}
private void btnCancle_Click(object sender, EventArgs e) //取消添加和修改的操作;
{
//控制按钮
EnableButton();
}
private void btnChoosePhoto_Click(object sender, EventArgs e)//选择图片展示在PictureBox中;
{
//打开一个路径,选择一个图片
OpenFileDialog openFile = new OpenFileDialog(); //打开文件
openFile.Filter = "图片|*.png;*.jpg;*.bmp"; //图片类型
if (openFile.ShowDialog() == DialogResult.OK)
{
photoName = openFile.FileName; //将文件名称保存到photoName ,以便在另存为时 查看图像类型
pbCurrentPhoto.BackgroundImage = Image.FromFile(openFile.FileName); //打开并展示
}
}
private void btnClose_Click(object sender, EventArgs e) //退出
{
DialogResult result = MessageBox.Show("系统退出,是否保存修改", "系统提示", MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// 执行保存;
// 【1】清空;
File.WriteAllText(fileName, string.Empty);
//【2】 把objList逐行写入
StreamWriter sw = new StreamWriter(fileName, true, Encoding.Default);
foreach(string item in objListStudent)
{
sw.WriteLine(item);
}
sw.Close();
//写入完成
MessageBox.Show("写入完成!!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//退出
Close();
}
//用户自定义方法;
private List<string> ReadFileToList(string filePath) //把某一个文件数据读取,并以List方法返回给调用者;
{
List<string> objList =new List<string>();
string line=string .Empty;
try
{
//一行行读取文件,
StreamReader file =new StreamReader(filePath, Encoding.Default);
while ( (line= file.ReadLine())!= null)
{
objList.Add(line);
//line = file.ReadLine();
}
file.Close();
}
catch (Exception ex)
{
throw ex;
}
return objList;
}
private void LoadDataToDataGrid(List<string> objList)//把List中的数据展示在DataGridView中;
{
//依次读取List中数据;
foreach (string item in objList)
{
string[] studentArray = item.Split(','); //读取的每一行,以逗号分隔开;
//把读取的当前学生插入到DataGridView中;
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dgvStudent);
row.Cells[0].Value = studentArray[0];
row.Cells[1].Value = studentArray[1];
row.Cells[2].Value = studentArray[2];
row.Cells[3].Value = studentArray[3];
row.Cells[4].Value = studentArray[4];
dgvStudent.Rows.Add(row);
}
}
private void LoadDataToDetail(string sno, string name,string sex,string birthday,string mobile,string email,
string homeAddress,string photo)//把一个学生的明细展示在明细groupbox中;
{
txtNO.Text = sno;
txtName.Text = name;
if (sex == "男") rbMale.Checked = true;
else rbFemale.Checked = true;
dtpBirthday.Text = birthday;
txtMobile.Text = mobile;
txtEmali.Text = email;
txtHomeAddress.Text = homeAddress;
if (photo == string.Empty) pbCurrentPhoto.BackgroundImage = null;
else pbCurrentPhoto.BackgroundImage = Image.FromFile(photo);
}
private string GetStudentBySNO(string sno) //根据学号查找某个学生的具体信息;
{
string currentStudent =string.Empty;
foreach (string item in objListStudent)
{
if (item.StartsWith(sno))
{
currentStudent = item;
break;
}
}
return currentStudent;
}
private void DisableButton()//禁用按钮
{
//禁用按钮
btnAdd.Enabled = false;
btnImport.Enabled = false;
btnUpdate.Enabled = false;
btnDelete.Enabled = false;
//启用groubbox
gboxStudentDetail.Enabled = true;
}
private void EnableButton()//启用按钮
{
//启用按钮导入添加、修改、删除;
btnAdd.Enabled = true;
btnImport.Enabled = true;
btnUpdate.Enabled = true;
btnDelete.Enabled = true;
//禁用groubbox
gboxStudentDetail.Enabled = false;
}
private bool ValiDate() //用户添加和修改后数据的校验
{
bool b = true;
//学号和姓名不能为空,学号不能重复(添加的时候);
if (string.IsNullOrWhiteSpace(txtNO.Text)) //学号是否为空;
{
MessageBox.Show("学号不能为空!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtNO.Focus(); //让学号的文本框获得焦点
b=false;
}
if(string.IsNullOrWhiteSpace(txtName.Text))//姓名是否为空;
{
MessageBox.Show("姓名不能为空!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtName.Focus();
b=false;
}
if(actionFlag == 1) //如果是添加操作
{
//通过方法 判断学号是否重复
if (GetStudentBySNO(txtNO.Text.Trim( ))!=string .Empty)
{
MessageBox.Show("该学号已经存在,请重新输入学号!", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtName.Focus();
b=false;
}
}
return b;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
private void label11_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click_1(object sender, EventArgs e)
{
}
private void txtEmali_TextChanged(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void pictureBox2_Click(object sender, EventArgs e)
{
}
private void gboxStudentQuery_TextChanged(object sender, EventArgs e)
{
}
private void pbCurrentPhoto_Click(object sender, EventArgs e)
{
}
}
}
参考:1. Here