How to fill a DataGridView without freezing the UI thread

G

Guest

The auto-generated line of code to fill a DataGridView once it is placed on
the designer surface in VS2005 is typically:

this.xyzTableAdapter.Fill(this.myDataSet.MyMember);

But if the query takes a long time to run, this freezes the UI (in a Windows
Forms application). What is the best practice for filling a DataGridView
without freezing the UI?
 
M

Marc Gravell

Actually, that is filling a DataSet/DataTable, not a DataGridView; to
do this without blocking, simply don't attach the set/table to the
DataGridView (as DataSource), and populate it on a non-UI thread, then
jump back when full to populate.

Something like (untested):

void fillButton_Click(object sender, EventArgs args) { // called on UI
thread
// may need to detach DataSource here (if present) or suspend
binding (RaiseListChangedEvents?)
myDataGridView.DataSource = null;

// spawn some work in the background
ThreadPool.QueueUserWorkItem(FillData);
}

void FillData(object state) { // called on background thread
this.xyzTableAdapter.Fill(this.myDataSet.MyMember);
// OK; have some data; attach the DataSource (need to jump to UI
thread):

this.Invoke((MethodInvoker) delegate {
myDataGridView.DataSource = myDataSet; // or table
});
}
 
G

Guest

Your approach sounds reasonable, Marc. Unfortunately, I will not be able to
test it out on a very timely basis, so I am marking your post as "providing
the answer" now...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top