简体   繁体   中英

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 :

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM