C# Refresh/Update databound control after executing SQL query

2k views Asked by At

I have a databound datagridview for a simple application. I am using the built-in visual studio database, but am using SQL queries to manipulate the data as I prefer it. The datagrid view is only databound because it is a requirement.

After executing any the datagridview does not update by itself, however even after much research and testing everything I could find, nothing seems to work. The data only updates after I restart the program.

This is what I currently have:

dgvEmployee.DataSource = null;
dgvEmployee.Rows.Clear();
this.employeeBindingSource.ResetBindings(true);
dgvEmployee.DataSource = this.employeeBindingSource;

I know it is not the fault of my queries since opening the database shows the added values. Thank you for your time. This is my first question on this site so please go easy on me ;)

2

There are 2 answers

0
Vojtěch Dohnal On

I am using this code and it is working well, but not sure if it is a best practice:

List<MyEmployeeData> lstDataSource = query.ToList();
dgvEmployee.DataSource = new BindingListView<MyEmployeeData>(lstDataSource);
dgvEmployee.Refresh();

It uses BindingListView class available via NuGet.

In your code theese two lines

dgvEmployee.DataSource = null;
dgvEmployee.Rows.Clear();

are in my opinion not necessary.

But you are missing something like this:

this.employeeBindingSource.DataSource = tableWithNewData;
0
ryancdotnet On

Have you tried refreshing the main form UI right after? Something like this:

dgvEmployee.DataSource = null;
dgvEmployee.DataSource = this.employeeBindingSource;
this.Refresh();
this.Update();