• 保存GRID数据示例

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; namespace 保存GRID数据示例 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { //提示是否修改 #region//--------修改数据就将数据保存并显示 if (MessageBox.Show("是否保存数据?", "系统消息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { #region ..........这里是保存数据代码 //结束编辑 dataGridView1.EndEdit(); //重新用表格数据填充数据容器 OleDbDataAdapter Ada = new OleDbDataAdapter(); DataTable table = (DataTable)dataGridView1.DataSource; //重新启动连接 String ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "/驱动.mdb"; //用Buider方法更新数据 using (OleDbConnection connection = new OleDbConnection(ConnectionString)) { Ada.SelectCommand = new OleDbCommand("SELECT * FROM 表", connection); OleDbCommandBuilder builder = new OleDbCommandBuilder(Ada); Ada.UpdateCommand = builder.GetUpdateCommand(); try { //更新数据表数据时 Ada.Update(table); table.AcceptChanges(); MessageBox.Show("操作已成功!数据将全部被保存......", "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); } catch (System.Data.OleDb.OleDbException ex) { throw new Exception(ex.Message); } } #endregion } #endregion #region //--------不修改就初始化显示以前数据 else { MessageBox.Show("用户取消操作,数据将恢复到初始状态......"); OleDbConnection A = new OleDbConnection(); A.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "/驱动.mdb"; try { A.Open(); DataSet B = new DataSet(); string sqlStr = "Select * from 表"; OleDbDataAdapter C = new OleDbDataAdapter(sqlStr, A); C.Fill(B); dataGridView1.DataSource = B.Tables[0]; } catch (System.Data.OleDb.OleDbException ex) { throw new Exception(ex.Message); } finally { A.Close(); } } #endregion } private void button1_Click(object sender, EventArgs e) { OleDbConnection A = new OleDbConnection(); A.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Windows.Forms.Application.StartupPath + "/驱动.mdb"; try { A.Open(); DataSet B = new DataSet(); string sqlStr = "Select * from 表"; OleDbDataAdapter C = new OleDbDataAdapter(sqlStr, A); C.Fill(B); dataGridView1.DataSource = B.Tables[0]; } catch (System.Data.OleDb.OleDbException ex) { throw new Exception(ex.Message); } finally { A.Close(); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } } }

    0
    204
    5KB
    2017-12-23
    12
上传资源赚积分or赚钱