[英]How to do Automatic synchronize between database access and DatagridView in c#
in my program when i delete a record, it deleted from database access and from the DataGridView , but when i close the window and open it again the record appear again in DataGridView ,Although it deleted from database access ,Here is my code : 在我的程序中,当我删除一条记录时,它已从数据库访问和DataGridView中删除,但是当我关闭窗口并再次打开它时,该记录再次出现在DataGridView中,尽管它已从数据库访问中删除,这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
command.Connection = connection;
string query = " delete from Hoteldb where ID= " +textBox0.Text + "";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
public void BindGridView()
{
string strSQL = "SELECT * FROM Hoteldb";
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
dataGridView1.DataSource = table;
connection.Close();
}
Try this : 尝试这个 :
private void button1_Click(object sender, EventArgs e)
{
int RowsAffected = 0;
connection.Open();
string query = "DELETE FROM Hoteldb WHERE ID=@ID";
command = new OleDBCommand(query);
command.Connection = connection;
cmd.Parameters.Add(new OleDbParameter("@ID", OleDbType.WChar, 150, "ID"));
cmd.Parameters["@ID"].Value = textBox0.Text.Trim()
RowsAffected = command.ExecuteNonQuery();
if(RowsAffected > 0)
{
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
else
{
MessageBox.Show("There was nothing to be deleted");
}
}
public void BindGridView()
{
connection.Open();
string strSQL = "SELECT * FROM Hoteldb";
cmd = new OleDbCommand(strSQL);
cmd.Connection = connection;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Hoteldb");
dataGridView1.DataSource = ds.Tables["Hoteldb"].DefaultView
connection.Close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.