一、DataGridView绑定数据库之后直接对其进行操作:
1.在按钮添加更新操作代码(只需一行):
this.tbTableAdapter.Update(this.abcDataSet2.tb);
其中abc为数据库名,tb为表名
2.在按钮添加删除操作代码:
DialogResult dlResult = MessageBox.Show(this, "要删除这些记录吗?", "请确认",
MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign); if (dlResult == DialogResult.Yes) { int j = dataGridView1.SelectedRows.Count; int[] l = new int[j];int i;
for (i = 0; i < j; i++) { l[i] = dataGridView1.SelectedRows[i].Index; }int k = 0;
while (k < j) { this.abcDataSet2.tb.Rows[l[k]].Delete(); k++; }二、DataGridView绑定数据库,把查询结果进行更新、删除操作后保存到数据库:
1.在按钮添加更新操作代码:
if (MessageBox.Show("确实要修改数据库吗?", "决策提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{DataTable dt = dataGridView1.DataSource as DataTable;
if (dt != null) { try { using (SqlConnection con = new SqlConnection("data source=ksig;initial catalog=AMDMS;user id=sa;pwd=123;")) { SqlDataAdapter da = new SqlDataAdapter("select * from account", con); SqlCommandBuilder scb = new SqlCommandBuilder(da); DataSet ds = new DataSet(); da.Fill(ds, "account"); da.Update(dt); } } catch (DataException de) { // } } MessageBox.Show("成功修改数据库!", "恭喜"); } else { MessageBox.Show("放弃修改数据库!", "系统提示"); }2.在按钮添加删除操作代码:
//在DataGridView1界面上进行可视化删除
dataGridView1.Rows.Remove(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex]); //把删除后的DataGridView1的结果更新到数据库中 DataTable dt = dataGridView1.DataSource as DataTable; if (dt != null) { try { using (SqlConnection con = new SqlConnection("data source=ksig;initial catalog=AMDMS;user id=sa;pwd=123;")) { SqlDataAdapter da = new SqlDataAdapter("select * from account", con); SqlCommandBuilder scb = new SqlCommandBuilder(da); DataSet ds = new DataSet(); da.Fill(ds, "account"); da.Update(dt); } } catch (DataException de) { // } }