DataTable的AcceptChanges()和RejectChanges()方法介绍并实现DataGridView数据增、删、改

  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;

  using System.Data.SqlClient;

  using System.Configuration;

  namespace DataRowStateDemo

  {

  public partial class FrmMain : Form

  {

  public FrmMain()

  {

  InitializeComponent();

  }

  //连接字符串

  string strConn = ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;

  ///

  /// 加载

  ///

  ///

  ///

  private void btn_LoadData_Click(object sender, EventArgs e)

  {

  Initdgv();

  this.btn_Add.Visible = false;

  }

  ///

  /// 初始化DataGridView

  ///

  private void Initdgv()

  {

  SqlConnection conn = new SqlConnection(strConn);

  string strSQL = "select * from Users";

  SqlCommand cmd = new SqlCommand(strSQL, conn);

  SqlDataAdapter adapter = new SqlDataAdapter(cmd);

  DataSet dsDgv = new System.Data.DataSet();

  try

  {

  conn.Open();

  //填充数据

  adapter.Fill(dsDgv);

  this.dgv_Demo.DataSource = dsDgv.Tables[0];

  //不显示最后的空行

  this.dgv_Demo.AllowUserToAddRows = false;

  // 设置第一列只读

  this.dgv_Demo.Columns[0].ReadOnly = true;

  }

  catch (Exception ex)

  { }

  finally

  {

  conn.Close();

  }

  }

  ///

  /// 编辑

  ///

  ///

  ///

  private void btn_Edit_Click(object sender, EventArgs e)

  {

  this.dgv_Demo.AllowUserToAddRows = true;

  }

  ///

  /// 保存

  ///

  ///

  ///

  private void btn_Save_Click(object sender, EventArgs e)

  {

  DataTable dtCopy = this.dgv_Demo.DataSource as DataTable;

  DataSet dsUsers = new DataSet();

  //产生与表Users结构相同的空表

  DataTable dtAdd = GetEmptyTable();

  DataTable dtEdit = GetEmptyTable();

  DataTable dtDel = GetEmptyTable();

  //根据DataRowState的状态获取新增、修改、删除的表数据

  dtAdd = dtCopy.GetChanges(DataRowState.Added);

  dtEdit = dtCopy.GetChanges(DataRowState.Modified);

  dtDel = dtCopy.GetChanges(DataRowState.Deleted);

  //新增

  if (dtAdd != null)

  {

  dtAdd.TableName = "Added";

  dsUsers.Tables.Add(dtAdd);

  }

  //修改

  if (dtEdit != null)

  {

  dtEdit.TableName = "Edit";

  dsUsers.Tables.Add(dtEdit);

  }

  //删除

  if (dtDel != null)

  {

  dtDel.TableName = "Del";

  dtDel.RejectChanges();

  dsUsers.Tables.Add(dtDel);

  }

  //保存数据

  if (SaveUser(dsUsers))

  {

  MessageBox.Show("保存成功!");

  //重新加载数据

  Initdgv();

  }

  else

  {

  MessageBox.Show("保存失败!");

  }

  }

  ///

  /// 根据表结构产生空表

  ///

  ///

  private DataTable GetEmptyTable()

  {

  DataTable dtTable = new DataTable("Users");

  //使用集合初始化器添加列

  dtTable.Columns.AddRange(new DataColumn[]{

  new DataColumn("UserID",typeof(Int32)),

  new DataColumn("UserName",typeof(string)),

  new DataColumn("Password",typeof(string)),

  new DataColumn("Sex",typeof(Char)),

  new DataColumn("Birthday",typeof(DateTime))

  });

  return dtTable;

  }

  ///

  /// 保存数据

  ///

  ///

  ///

  private bool SaveUser(DataSet ds)

  {

  bool tf = false;

  //新增

  if (ds.Tables["Added"] != null)

  {

  foreach (DataRow dr in ds.Tables["Added"].Rows)

  {

  tf= InsertUser(dr);

  }

  }

  //修改

  if (ds.Tables["Edit"] != null)

  {

  foreach (DataRow dr in ds.Tables["Edit"].Rows)

  {

  tf = UpdateUser(dr);

  }

  }

  //删除

  if (ds.Tables["Del"] != null)

  {

  foreach (DataRow dr in ds.Tables["Del"].Rows)

  {

  tf = DeleteUser(dr);

  }

  }

  return tf;

  }

  ///

  /// 数据库增加

  ///

  ///

  ///

  private bool InsertUser(DataRow drDataRow)

  {

  string strSQL = string.Format(@"insert into users values('{0}','{1}','{2}','{3}')", drDataRow["UserName"].ToString(), drDataRow["Password"].ToString(), drDataRow["Sex"].ToString(), drDataRow["Birthday"].ToString());

  return ExecuteSQL(strSQL);

  }

  ///

  /// 数据库删除

  ///

  ///

  ///

  private bool DeleteUser(DataRow drDataRow)

  {

  string strSQL = string.Format("delete from users where UserID='{0}'", Convert.ToInt32(drDataRow["UserID"].ToString()));

  return ExecuteSQL(strSQL);

  }

  ///

  /// 数据库修改

  ///

  ///

  ///

  private bool UpdateUser(DataRow drDataRow)

  {

  string strSQL = string.Format("update users set UserName='{0}',Password='{1}',Sex='{2}',Birthday='{3}' where UserID='{4}'",

  drDataRow["UserName"].ToString(), drDataRow["Password"].ToString(), drDataRow["Sex"].ToString(),

  drDataRow["Birthday"].ToString(), Convert.ToInt32(drDataRow["UserID"].ToString()));

  return ExecuteSQL(strSQL);

  }

  ///

  /// 数据库执行SQL语句

  ///

  ///

  ///

  private bool ExecuteSQL(string strSQL)

  {

  bool tfResult = false;

  SqlConnection conn = new SqlConnection(strConn);

  SqlCommand cmd = new SqlCommand(strSQL, conn);

  try

  {

  conn.Open();

  tfResult= cmd.ExecuteNonQuery().Equals(1);

  }

  catch (Exception ex)

  { }

  finally

  {

  conn.Close();

  }

  return tfResult;

  }

  ///

  /// 删除

  ///

  ///

  ///

  private void btn_Del_Click(object sender, EventArgs e)

  {

  if (this.dgv_Demo.SelectedRows.Count <= 0)

  {

  MessageBox.Show("请先选择要删除的行");

  }

  else

  {

  foreach(DataGridViewRow dr in this.dgv_Demo.SelectedRows)

  {

  //只是删除DataGridView中显示的数据,并没有删除数据库中的数据

  this.dgv_Demo.Rows.Remove(dr);

  }

  }

  }

  ///

  /// 增加空行

  ///

  ///

  ///

  private void btn_Add_Click(object sender, EventArgs e)

  {

  //DataGridView没有绑定数据时才可以使用Add()方法增加空行

  this.dgv_Demo.Rows.Add();

  }

  private void FrmMain_Load(object sender, EventArgs e)

  {

  this.dgv_Demo.AllowUserToAddRows = false;

  }

  }

  }