[英]How to do Automatic synchronize between database access and DatagridView in c#
在我的程序中,當我刪除一條記錄時,它已從數據庫訪問和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();
}
嘗試這個 :
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.