Refreshing a DataGridView after DB has changed?

2019-08-23 22:15发布

问题:

I need to "refresh" a DataGridView, bound to a database table, on a form within a TabControl The DataGridView is loaded correctly on startup... But if the data in the DataBase change, How do I refresh it to reflect new records or updates?

this is what I am doing in code, after looking for some examples on the web:

    MyTabBindingSource.EndEdit()
    Me.MyTableAdapter.ClearBeforeFill = True

    Me.MyTableAdapter.Fill(Me.MyDataSet.MyTable)

    MyDataGridView.Update()
    MyDataGridView.Refresh()

but nothing changes at all...Do I need to refresh/repaint the TabControl as well as the Form containing it? or what else??

回答1:

Assuming the datagridview is bound to myTable in the dataset, calling the update() may be the problem. Try getting rid of this.

If that doesn't work try rebinding to mytable again and refresh the DGV.

You shouldn't need to refresh the tab or form.



回答2:

I'm assuming you have edited the data straight from datagridview and updated it into the server.

You can get/view the updated ones by ticking the "Enable Editing" from datagridview's properties.

Datagridview Tasks

Enable Adding
Enable Editing -- check this one
Enable Deleting
Enable Column Reordering

Once you run your code that clears and fills the datagridview, you will have the new ones.



回答3:

The way I do this is I clear the DataGridView's DataSource then re-bind it again.
Try:

MyDataGridView.DataSource = Nothing
MyDataGridView.Rows.Clear
MyDataGridView.DataSource = MyTable?