【问题标题】:How to update listview after Form.Show如何在 Form.Show 之后更新列表视图
【发布时间】:2012-01-04 03:14:09
【问题描述】:

我有一个带有列表视图的表单。调用 Form.Show 后,我需要更新我的列表视图。但是,无论我的列表视图代码如何,在调用 Form.Show 之后,它都是空的,没有列,没有数据。如果我将 Form.Show 移动到我的 listview 代码之后,则 listview 会正确显示。

这是我的列表视图代码:

private void InitializeListView()
{
    _snapshotList.BeginUpdate();
    _snapshotList.Items.Clear();
    foreach (ISnapshot snapshot in _snapshots)
    {
         string comment = InstanceFactory<ProjectRecoveryService>.Instance.RetrieveCommentsforSnapshot(snapshot);

         string[] sub = new string[] { snapshot.Name, snapshot.Version.ToString(), snapshot.CreatedDate.ToString(), comment };
         ListViewItem item = new ListViewItem(sub);
         item.Tag = snapshot;
         this._snapshotList.Items.Add(item);
    }
    _snapshotList.EndUpdate();
    this._snapshotList.Refresh();
}

附带说明,我有另一个非常相似的表单,但有一个其他人扩展的 TreeView,可以按需要工作。

有什么想法吗?

编辑 1 此表单需要是单个实例。阅读this post 后,我的 Form.Show 代码结构如下:

        public static RestoreSnapshotDialog GetInstance()
        {
            if (_dialog == null)
            {
                _dialog = new RestoreSnapshotDialog();
                _dialog.Show(Control.FromHandle(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle));
            }
            else
            {
                _dialog.BringToFront();
            }
            return _dialog;
        }

在 FormClosed 事件中,我设置了 _dialog = null。

【问题讨论】:

  • 什么时候填充_snapshots?
  • 它在 Form.Show 之后填充。填充 _snapshots 会触发上述方法。
  • 那么Form.Show与问题无关?何时调用填充。对相关例程进行一些调试,确保您认为正在发生的事情正在发生。这将是一个“doh”时刻,您发布的代码看不到任何问题。
  • 听起来您调用 Show() 的方式或触发 listview 代码的方式有问题。你没发的东西。使用调试器,在这个方法上放一个断点。并确保您实际上是在更新用户正在查看的表单对象,而不是 另一个 从未调用过 Show() 方法的对象。

标签: c# winforms .net-3.5


【解决方案1】:

您必须处理Form.Shown 事件才能更新列表视图。

【讨论】:

  • 对不起...没有关注。我该怎么办这个活动?触发此事件时运行我的 InitializeListView 方法?
  • 我修改了我的代码,在 Form.Shown 事件中运行上述 InitializeListView 方法。仍然与原始帖子中的结果相同。
【解决方案2】:

我能找到的唯一解决方案是在我的列表视图完全填充后调用 Form.Show()。所以我通过覆盖 Form.Show 来创建自己的 Form.Show。

public new void Show()
{
    if (_showdialog)
    {
        _dialog.Show(Control.FromHandle(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle));
    }
    else
    {
        _dialog.BringToFront();
    }
}

在我的列表视图解决了我的问题后调用此方法。但是,我的所有其他对话框(不使用列表视图)都可以使用原始帖子中的代码按预期工作。感谢 Hans Passant 引导我找到这个解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多