【问题标题】:Gridview column count always 0 at startupGridview 列数在启动时始终为 0
【发布时间】:2023-04-05 08:40:01
【问题描述】:

下面的代码在我的应用程序启动时被调用。数据源确实有 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 ??? !!");

}

【问题讨论】:

    标签: c# multithreading gridview radgrid


    【解决方案1】:

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

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

    根据您的要求,这里是使用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 ??? !!");
    }
    

    【讨论】:

    • 如何等待异步操作完成?
    • @user1438082 你在你的radGridViewFiles 上打电话给EndInvoke。此调用将阻塞,直到操作完成。
    • 这是正确的做法吗?根据您的反馈阅读了有关 Async 和 Await 的反馈,并且没有网站提及 endinvoke ?如果我确实需要 endinvoke,那么您能否准确指定所需的代码行。
    • 这是一种方法。断章取义很难说是对是错。首先,我会质疑在启动时以异步方式运行绑定的需要。如果你真的需要它。如果您在 BeginInvoke 之后立即调用 EndInvoke,在相同的方法中,在用户体验方面将是相同的结果 - gui 线程将被阻止(假设您从 gui 线程调用)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2013-04-22
    • 2011-02-18
    • 2014-05-02
    相关资源
    最近更新 更多