开发者

Datagridview won't refresh after deleting a record from database

开发者 https://www.devze.com 2023-02-22 13:01 出处:网络
Why won\'t it refresh? private void deleteRecord() { if (BooksGrid.SelectedRows.Count > 0) { int selectedIndex = BooksGrid.SelectedRows[0].Index;

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号