c# datagirdview 表格,删除一条记录,没有直接更新掉。需要退出该窗口,再进入确实删除了。
获得表格代码如下:
oleConnection1.Open();
string sql = "select * from txt ";
OleDbDataAdapter thisAdapter = new OleDbDataAdapter(sql, oleConnection1);
DataSet thisDataSet = new System.Data.DataSet();
thisAdapter.Fill(thisDataSet, "table");
DataTable dt = thisDataSet.Tables["table"];
dataGridView1.DataSource = dt;
string sql = "delete from txt where id" + "="+dgv.Rows[e.RowIndex].Cells[0].Value.ToString().Trim()+"";
OleDbCommand cmd = new OleDbCommand(sql, oleConnection1);
cmd.ExecuteNonQuery();
MessageBox.Show("删除成功");
有什么办法,删除后,直接体现出来。 不需要退出窗口,再进入。
请各位积极回复,非常感谢,望能有详细代码。
private void Delete_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("数据库连接串");
conn.Open();
SqlDataAdapter daAuthors = new SqlDataAdapter("Select * From student", conn);
DataSet dsPubs = new DataSet("Pubs");
daAuthors.FillSchema(dsPubs, SchemaType.Source, "student");
daAuthors.Fill(dsPubs, "student");
DataTable tblAuthors;
tblAuthors = dsPubs.Tables["student"];
if (MessageBox.Show("确实要删除该行吗?", "询问", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
DataRow drCurrent;
string Row_zhi = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//获取第一个单元格的值
//MessageBox.Show(Row_zhi);
drCurrent = tblAuthors.Rows.Find(Row_zhi);
drCurrent.Delete();
SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors); //SqlCommandBuilder 提供自动生成单表命令的一种方式,这些命令用于协调使用关联的 SQL Server 数据库对 DataSet 执行的更改。
daAuthors.Update(dsPubs, "student"); //数据适配器.Update()方法
//MessageBox.Show("数据库更新成功!");
//-------重新绑定dataGridView的数据源,以便重新显示-------
daAuthors.Fill(dsPubs, "student");
DataTable tblAuthors1;
tblAuthors1 = dsPubs.Tables["student"];
dataGridView1.DataSource = tblAuthors1;
}
conn.Close();
conn.Dispose();
//MessageBox.Show("数据库连接已关闭");
}
一个示例,可以参考
string sql = "delete from txt where id" + "="+dgv.Rows[e.RowIndex].Cells[0].Value.ToString().Trim()+"";
OleDbCommand cmd = new OleDbCommand(sql, oleConnection1);
cmd.ExecuteNonQuery();
Update();//Forces the control to paint any currently invalid areas.
MessageBox.Show("删除成功");
update() 方法代码有否! 麻烦分享一下。
你删除的是数据库的内容,本质上表格绑定的DataTable毫无变化,建议写代码,删除DataTable里对应的行