如何在Form.Show之后更新listview

时间:2011-12-30 13:09:27

标签: c# winforms .net-3.5

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我能找到的唯一解决方案是在我的listview完全填充之后调用Form.Show()。所以我通过覆盖Form.Show。

来创建我自己的Form.Show
public new void Show()
{
    if (_showdialog)
    {
        _dialog.Show(Control.FromHandle(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle));
    }
    else
    {
        _dialog.BringToFront();
    }
}

在listview解决我的问题后调用此方法。但是,我的所有其他对话框(不使用listview)与原始帖子中的代码一样按预期工作。感谢Hans Passant带领我找到这个解决方案。