469,643 Members | 2,061 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,643 developers. It's quick & easy.

How to fill a DataGridView without freezing the UI thread

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?
Apr 20 '07 #1
2 11225
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
});
}

Apr 20 '07 #2
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...

"Marc Gravell" wrote:
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
});
}

Apr 23 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by | last post: by
reply views Thread by =?Utf-8?B?SEdK?= | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.