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查詢語句中必須要包含有表的主鍵 否則更改數據的時候會報錯
