Gridview列计数在启动时始终为0

时间:2014-02-23 17:17:36

标签: c# multithreading gridview radgrid

我的应用程序启动时下面的代码被调用。数据源确实有1个项目。但是永远不会显示消息框。现在,当第一次绘制用户界面时,gridview确实有一行。如果我在按钮上再次调用代码,则会正确显示消息框。这里发生了什么以及如何解决它(我认为它与线程有关,因为radGridview还没有实际更新)?

C#代码绑定网格

// Bind list to gridview
this.radGridViewFiles.BeginInvoke((MethodInvoker)(() => this.radGridViewFiles.DataSource = null));
this.radGridViewFiles.BeginInvoke((MethodInvoker)(() => this.radGridViewFiles.DataSource = MyGlobals.ListOfItemsToControl.Concat(MyGlobals.lstNewItems.Where(i => i.sItemRequestStatus == "Add").ToList()))); //

if (radGridViewFiles.Columns.Count > 0)
{
   RadMessageBox.Show(" This messagebox should show on startup but it does not - But if i call all this code again manually on a button press it does show ??? !!");

}

1 个答案:

答案 0 :(得分:2)

您正在异步绑定GridView,这就是为什么当您检查列计数时它仍然为零。

我建议你将它绑定在同一个线程中或等待异步操作完成。

根据您的要求,这是使用EndInvoke的代码示例。虽然如果你把这一切都放在一个方法中 - 你将无法从异步调用中获得任何东西。

// You don't need this, so i commented it out.
// it's excessive, you are going to overwrite this variable anyway
// this.radGridViewFiles.BeginInvoke((MethodInvoker)(() =>this.radGridViewFiles.DataSource = null));

var asyncRes = this.radGridViewFiles.BeginInvoke((MethodInvoker)(() => this.radGridViewFiles.DataSource = MyGlobals.ListOfItemsToControl.Concat(MyGlobals.lstNewItems.Where(i => i.sItemRequestStatus == "Add").ToList())));

// This method blocks until previous operation is done
// It's quite pointless. In real life you should call it somewhere from another thread
// While qui thread is unblocked and displaying progress bar or something like this. 
this.radGridViewFiles.EndInvoke(asyncRes);

// at this point, binding is complete
if (radGridViewFiles.Columns.Count > 0)
{
   RadMessageBox.Show(" This messagebox should show on startup but it does not - But if i call all this code again manually on a button press it does show ??? !!");
}