1.将项目下的App.config文件打开,修改里面的内容,存储连接字符串
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add connectionString="Data Source=LENOVO-PC;Initial Catalog=MyDatabase;Integrated Security=True" name="strCon" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>
2.右键项目下的引用,添加引用,程序集System.Configuration,确定。
3.封装SqlHelper类,用于数据库增删改查操作,一定添加引用System.Configuration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
namespace 大项目
{
public class SqlHelper
{
private static readonly string str = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
public static int ExecuteNonQuery(string sql,params SqlParameter[] ps)
{
using (SqlConnection con=new SqlConnection(str))
{
using (SqlCommand cmd=new SqlCommand(sql,con))
{
con.Open();
cmd.Parameters.AddRange(ps);
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql, params SqlParameter[] ps)
{
using (SqlConnection con =new SqlConnection(str))
{
using (SqlCommand cmd=new SqlCommand(sql,con))
{
con.Open();
cmd.Parameters.AddRange(ps);
return cmd.ExecuteScalar();
}
}
}
public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] ps)
{
SqlConnection con = new SqlConnection(str);
using (SqlCommand cmd=new SqlCommand(sql,con))
{
cmd.Parameters.AddRange(ps);
try
{
con.Open();
return cmd.ExecuteReader();
}
catch (Exception ex)
{
con.Close();
con.Dispose();
throw ex;
}
}
}
}
}
4.封装Student类,用于数据库转对象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 大项目
{
public class Student
{
//tsid, tsname, tsgender, tsadress, tsage
private int _tSId;
private string _tSName;
private char _tSGender;
private string _tSAdress;
private int _tSAge;
public int TSId
{
get
{
return _tSId;
}
set
{
_tSId = value;
}
}
public string TSName
{
get
{
return _tSName;
}
set
{
_tSName = value;
}
}
public char TSGender
{
get
{
return _tSGender;
}
set
{
_tSGender = value;
}
}
public string TSAdress
{
get
{
return _tSAdress;
}
set
{
_tSAdress = value;
}
}
public int TSAge
{
get
{
return _tSAge;
}
set
{
_tSAge = value;
}
}
}
}
5.Form代码
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.Data.SqlClient;
namespace 大项目
{
public partial class Form1 : Form
{
MyEventArgs mea = new MyEventArgs();//自定义类,存储传值的参数(标识和对象)
public event EventHandler evt;//声明事件
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadStudent();
}
/// <summary>
/// 窗体加载时,显示数据库中的数据
/// </summary>
private void LoadStudent()
{
List<Student> list = new List<Student>();
string sql = "select tsid, tsname, tsgender, tsadress, tsage from student1";
Student stu = null;
using (SqlDataReader reader =SqlHelper.ExecuteReader(sql))
{
if (reader.HasRows)
{
while (reader.Read())
{
stu = ReaderDBtoStudent(reader);
list.Add(stu);
}
}
}
dgv.AutoGenerateColumns = false;
dgv.DataSource = list;
//dgv.SelectedRows[0].Selected = false;
}
/// <summary>
/// 封装数据库转对象的方法
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private Student ReaderDBtoStudent(SqlDataReader reader)
{
Student stu = new Student();
stu.TSId = Convert.ToInt32(reader["tsid"]);
stu.TSName = reader["tsname"].ToString();
stu.TSGender = Convert.ToBoolean(reader["tsgender"]) ? '男':'女';
stu.TSAdress = reader["tsadress"].ToString();
stu.TSAge = Convert.ToInt32(reader["tsage"]);
return stu;
}
/// <summary>
/// 新增按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, EventArgs e)
{
ShowStudentAddAndUpdate(1);
}
/// <summary>
/// 修改按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dgv.SelectedRows.Count>0)//SelectedRows表示选中的行的集合,选一行就是0,选两行就是【0,1】,以此类推
{
Student stu = new Student();
stu.TSAdress = dgv.SelectedRows[0].Cells[4].Value.ToString();//地址
stu.TSAge = Convert.ToInt32(dgv.SelectedRows[0].Cells[3].Value);//年龄
stu.TSGender = Convert.ToChar(dgv.SelectedRows[0].Cells[2].Value);//性别
stu.TSId = Convert.ToInt32(dgv.SelectedRows[0].Cells[0].Value);//id
stu.TSName = dgv.SelectedRows[0].Cells[1].Value.ToString();//姓名
mea.obj = stu;//把对象存起来,传值的时候用
ShowStudentAddAndUpdate(2);
}
else
{
MessageBox.Show("请先选择要修改的行");
}
}
/// <summary>
/// 封装的显示子窗体的方法
/// </summary>
/// <param name="p"></param>
private void ShowStudentAddAndUpdate(int p)
{
StudentAddAndUpdate sau = new StudentAddAndUpdate();
this.evt += new EventHandler(sau.SetText);//给这个方法注册事件,
//意思就是说执行这个方法就会触发该事件并执行相应的事件处理方法
mea.Temp = p;//将标识存起来
if (this.evt!=null)
{
this.evt(this,mea);//触发事件时发生,参数this表示谁触发的事件,mea表示向事件处理方法传递参数
sau.FormClosed += new FormClosedEventHandler(sau_FormClosed);//刷新,重新加载
sau.ShowDialog();
}
}
/// <summary>
/// 刷新,点击关闭按钮时,重新加载新增的或者修改以后的数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sau_FormClosed(object sender, FormClosedEventArgs e)
{
LoadStudent();
}
}
}
6.Form窗体