2012-10-14 73 views
1

我的代碼有問題,使用DataGridView編輯數據庫中的數據。使用datagridview更新數據庫中的數據C#

我在da.update(dt);它說的錯誤,

動態SQL生成的更新命令不抵抗 支持的SelectCommand不返回任何鍵列信息。

當我改變SELECTUPDATE/INSERT我在da.fill(dt);得到一個錯誤。

我的代碼有什麼問題?

這裏是我的代碼:

private void btnEdit_Click(object sender, EventArgs e) > { 
    con.Open(); 
    DataTable dt = new DataTable(); 
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM RegistrationTable", con); 
    da.Fill(dt); 
    dt.Rows[dgvREGtable.CurrentRow.Index].BeginEdit(); 
    dt.Rows[dgvREGtable.CurrentRow.Index][0] = tbFirstname.Text; 
    dt.Rows[dgvREGtable.CurrentRow.Index][1] = tbLastname.Text; 
    dt.Rows[dgvREGtable.CurrentRow.Index][2] = tbEmail.Text; 
    dt.Rows[dgvREGtable.CurrentRow.Index][3] = tbContacts.Text; 
    dt.Rows[dgvREGtable.CurrentRow.Index][4] = tbUsername.Text; 
    dt.Rows[dgvREGtable.CurrentRow.Index][5] = tbPassword.Text; 
    dt.Rows[dgvREGtable.CurrentRow.Index].EndEdit(); 
    SqlCommandBuilder cb = new SqlCommandBuilder(da); 
    da.Update(dt); 
    displayrecords(); 
    con.Close(); 
} 

回答

5

你的選擇查詢需要返回表的主鍵。如果你的表沒有主鍵,你需要設置一個。

+1

haha​​h tnx mate ..現在我知道我的問題是什麼.. – azzyloth

2

在我看來,最簡單的方法是將DataGridView實際綁定到數據集,然後綁定將爲您處理所有醜陋的東西。例如:

DataSet mydata = new DataSet(); 
// populate your dataset however you like 
DataBindingSource mybindingsource = new DataBindingSource(typeof(DataSet)); 
mybindingsource.DataSource = mydata; 
DataGridView mydatagridview = new DataGridView(); 
mydatagridview.DataSource = mybindingsource; 

這就是本質的方式,但它在設計者中更容易實現這一點。

相關問題