Datagridview won't refresh after deleting a record from database
Why won't it refresh?
private void deleteRecord()
{
if (BooksGrid.SelectedRows.Count > 0)
{
int selectedIndex = BooksGrid.SelectedRows[0].Index;
int rowID = int.Parse(BooksGrid[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM Books WHERE BookID = @RowID";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = Booksconnection;
deleteRecord.CommandType = CommandType.Text;
delete开发者_如何转开发Record.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "@RowID";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
deleteRecord.Connection.Close();
}
}
Without knowing exactly what your DataGridView
's DataSource
is, (and assuming the record has actually been deleted from the database) I would say you need to reset the DataSource
, whatever it may be.
For example, in my code, I usually have a DataTable
as my DataSource
and then I call DataTable.Clear()
to clear it out. Afterwards, I fill it back up with the database. This ensures my DataGridView
has a fully updated DataTable
as its DataSource
.
Dataset.GetChanges()
will only work when you've made the changes via the dataset - in this case you're doing it outside of its control, so you're going to have to actually reload the dataset yourself (or better still, call the method that populated it in the first place) - this way, you'll pick up changes from other users too...
精彩评论