[英]C# Sort Datagridview
I would like to sort my Datagridview
at the end of my DownloadFileCompleted event
.我想在我的DownloadFileCompleted event
结束时对我的Datagridview
进行排序。 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.我尝试了以下源代码,如果在buttonClick event
上调用它,它就可以工作,但它与我的DownloadFileCompleted event
无关,我不明白为什么。
// 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. dg_logiciel
未更新的原因是client_DownloadFileCompleted
方法正在被您用于在后台下载的任何内容异步调用。 This means that the the client_DownloadFileCompleted
method is being called by a different thread than the one that your datagridview
is on.这意味着client_DownloadFileCompleted
方法由与datagridview
所在的线程不同的线程调用。 The datagridview
is on the UI Thread
, and the client_DownloadFileCompleted
is being called by some Worker Thread
. datagridview
在UI Thread
,并且client_DownloadFileCompleted
正在被一些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.要解决这个问题,您需要向UI Thread
发送一些信息,告诉它需要执行某种操作。
This can be accomplished by calling <control>.Invoke(...)
as follows:这可以通过调用<control>.Invoke(...)
来完成,如下所示:
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.这会向UI Thread
发送一条消息,告诉它在有机会时调用您正在传递的delegate
。 In this case the delegate just has one unnamed method inside of it and all that method does is call dg_logiciel.Sort(...);
在这种情况下,委托内部只有一个未命名的方法,该方法所做的只是调用dg_logiciel.Sort(...);
The (MethodInvoker)
bit, for the sake of completeness, just casts the delegate as a MethodInvoker
type. (MethodInvoker)
位,为了完整起见,只是将委托转换为MethodInvoker
类型。
A short simple answer can be found here: How does Invoke work underneath?可以在这里找到一个简短的简单答案: Invoke 在下面如何工作?
I hope that helps clear it up at least a little.我希望这至少有助于清除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.