I would like to sort my Datagridview
at the end of my DownloadFileCompleted event
. I tried the following source which is working if it's called on a buttonClick event
, but it's not with my DownloadFileCompleted event
and I don't understand why.
// Does work
private void bt_test_1_Click(object sender, EventArgs e)
{
dg_logiciel.Columns[1].SortMode = DataGridViewColumnSortMode.Programmatic;
dg_logiciel.Sort(dg_logiciel.Columns[1], ListSortDirection.Ascending);
}
// Does not work
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
// mycode
dg_logiciel.Columns[1].SortMode = DataGridViewColumnSortMode.Programmatic;
dg_logiciel.Sort(dg_logiciel.Columns[1], ListSortDirection.Ascending);
}
Can someone explain me that?
The reason that dg_logiciel
does not get updated is that the the client_DownloadFileCompleted
method is being called asynchronously by whatever you're using to download in the background. This means that the the client_DownloadFileCompleted
method is being called by a different thread than the one that your datagridview
is on. The datagridview
is on the UI Thread
, and the client_DownloadFileCompleted
is being called by some Worker Thread
.
To get around this problem you need to send something over to the UI Thread
that tells it that it needs to perform some kind of action.
This can be accomplished by calling <control>.Invoke(...)
as follows:
dg_logiciel.Invoke((MethodInvoker) delegate(){ dg_logiciel.Sort(dg_logiciel.Columns[1], ListSortDirectionAscending);});
This sends a message over to the UI Thread
telling it call the delegate
you're passing whenever it gets a chance. In this case the delegate just has one unnamed method inside of it and all that method does is call dg_logiciel.Sort(...);
The (MethodInvoker)
bit, for the sake of completeness, just casts the delegate as a MethodInvoker
type.
A short simple answer can be found here: How does Invoke work underneath?
I hope that helps clear it up at least a little.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.