1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Data.SqlClient; 6 using System.Drawing; 7 using System.Linq; 8 using System.Text; 9 using System.Threading.Tasks; 10 using System.Windows.Forms; 11 12 namespace Message 13 { 14 public partial class FrmBank : Form 15 { 16 SqlConnection sqlConn = new SqlConnection("Data Source=.;Initial Catalog=Message;Integrated Security=True;"); 17 SqlDataAdapter da; 18 DataTable dt; 19 DataSet ds = new DataSet(); 20 21 public FrmBank() 22 { 23 InitializeComponent(); 24 } 25 26 private void frmBank_Load(object sender, EventArgs e) 27 { 28 da = new SqlDataAdapter("SELECT bid as '序号', name as '银行名称', number as '银行编号', address as '银行地址', contacts as '联系人', contactNumber as '联系电话' FROM Bank", sqlConn); 29 da.Fill(ds, "银行信息"); 30 dataGridView1.DataSource = ds.Tables["银行信息"]; 31 //然后用SqlCommandBuilder自动为SqlDataAdapter生成Insert、Update、Delete命令 32 SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(da); 33 } 34 35 private void btnUpdate_Click(object sender, EventArgs e) 36 { 37 if (ds.HasChanges()) 38 { 39 try 40 { 41 da.Update(ds.Tables["银行信息"]); 42 ds.Tables["银行信息"].AcceptChanges(); 43 MessageBox.Show("更新成功!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Information); 44 } 45 catch (Exception ex) 46 { 47 MessageBox.Show(ex.Message, "更新失败!", MessageBoxButtons.OK, MessageBoxIcon.Error); 48 } 49 } 50 } 51 52 private void btnDelete_Click(object sender, EventArgs e) 53 { 54 //删除首先要定位到当前选中的记录 55 int delRowIndex = dataGridView1.CurrentRow.Index; 56 if (delRowIndex != -1) 57 this.dataGridView1.Rows.RemoveAt(delRowIndex); 58 btnUpdate.PerformClick(); 59 } 60 61 private void btnQuit_Click(object sender, EventArgs e) 62 { 63 this.Dispose(); 64 } 65 } 66 }
以上代码这样写 更新一次可以成功 但是第二次更新时就会报错了
把代码 SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);这一行放到按钮的点击事件里就行了
private void btnUpdate_Click(object sender, EventArgs e) { if (ds.HasChanges()) { try { SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(da); da.Update(ds.Tables["银行信息"]); ds.Tables["银行信息"].AcceptChanges(); MessageBox.Show("更新成功!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Information); }
或者放在一个方法里 在需要的地方调用
private void UpdateData() { dt = dataGridView1.DataSource as DataTable; SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da); da.Update(dt); }
private void btnUpdate_Click(object sender, EventArgs e) { if (ds.HasChanges()) { try { UpdateData(); MessageBox.Show("更新成功!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Information); }
select查询语句中必须要包含有表的主键 否则更改数据的时候会报错