namespace CURD { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void toolStripButton1_Click(object sender, EventArgs e) { //新增 PersonEdit form = new PersonEdit(); form.Action = "AddNew"; form.ShowDialog(); LoadData();//新增完成,刷新界面 } private void Form1_Load(object sender, EventArgs e) { //禁止自动生成列 gridePersons.AutoGenerateColumns = false; //查询数据 LoadData(); } private void LoadData() { DataTable tab = MySqlHelper.ExecuteQuery("select id,name,age,if(gender,‘男‘,‘女‘) gender from t_persons"); gridePersons.DataSource = tab; } private void gridePersons_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataTable tab = (DataTable)gridePersons.DataSource; //得到选中的行数 DataRow row = tab.Rows[e.RowIndex]; //得到当前选中行的ID号 int id = (int)row["id"]; //点击的是哪一列 if (e.ColumnIndex == 0)//编辑 { PersonEdit form = new PersonEdit(); form.Action = "Edit"; form.EditingId = id; form.ShowDialog(); LoadData(); } else if (e.ColumnIndex == 1)//删除 { //提示用户是否要删除 if (MessageBox.Show("你真的要删除吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } //根据ID删除 MySqlHelper.ExecuteNonQuery("DELETE FROM t_persons WHERE id = @id", new MySqlParameter { ParameterName = "@id", Value = id }); //刷新数据 LoadData(); } } private void shuaxin_Click(object sender, EventArgs e) { LoadData(); } } }
using MySql.Data.MySqlClient; 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; namespace CURD { public partial class PersonEdit : Form { //新增数据传递 Action="AddNew" public string Action { get; set; } //编辑数据传递 Action = "Edit" EditingId=5 public int EditingId { get; set; } public PersonEdit() { InitializeComponent(); } private void PersonEdit_Load(object sender, EventArgs e) { if (Action == "Edit")//如果是编辑,则先加载旧的数据 { DataTable table = MySqlHelper.ExecuteQuery("select * from t_persons where [email protected]", new MySqlParameter { ParameterName="@id",Value=EditingId}); if (table.Rows.Count <= 0) { MessageBox.Show("找不到ID为"+EditingId+"的数据"); return; } //取得查询出来的数据 DataRow row = table.Rows[0]; txtName.Text = (string)row["name"]; txtAge.Text = (string)row["age"]; int gender = (int)row["gender"]; //判断是男还是女,男为第一列0 女为第二列1 txtGender.SelectedIndex = (gender==1?0:1); } } } }
时间: 2024-12-17 07:53:24