How can I make a ListView update after each item i

2019-06-02 05:52发布

I am trying to use a ListView to make a realtime log output to a windows form.

This is the dummy code:

 public Form1()
    {
        InitializeComponent();
        listView1.View = View.Details;
        listView1.GridLines = false;
        listView1.Scrollable = true;

        listView1.FullRowSelect = true;
        listView1.Columns.Add("Track");
        listView1.Columns.Add("Status");

        for (int i = 1; i <= 10000; i++)
        {
            ListViewItem LVI = new ListViewItem("Track " + i);
            LVI.SubItems.Add("Updated");
            listView1.Items.Add(LVI);
            listView1.TopItem = LVI;
            listView1.EnsureVisible(listView1.Items.Count - 1);
        }
    }

How can I set it so it refreshes after each line is added? At the moment the application waits until the list is generated and then loads the form with the complete list.

3条回答
唯我独甜
2楼-- · 2019-06-02 06:10

Refresh won't work as that will only update what was already in the listview, not the added items.

Perhaps you should look at this:

Listview items not showing

查看更多
相关推荐>>
3楼-- · 2019-06-02 06:13

You can fill data items in another thread (for example using task):

Application.DoEvents() ... processes all window messages and redraws component.

 public Form1()
        {
            InitializeComponent();
            listView1.View = View.Details;
            listView1.GridLines = false;
            listView1.Scrollable = true;

            listView1.FullRowSelect = true;
            listView1.Columns.Add("Track");
            listView1.Columns.Add("Status");

            Task t = new Task(new Action(() =>
                {
                    RefreshLines();
                }));
            t.Start();
        }

        public void RefreshLines()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(this.RefreshLines));
            }
            for (int i = 1; i <= 10000; i++)
            {
                ListViewItem LVI = new ListViewItem("Track " + i);
                LVI.SubItems.Add("Updated");
                listView1.Items.Add(LVI);
                listView1.TopItem = LVI;
                listView1.EnsureVisible(listView1.Items.Count - 1);
                Application.DoEvents();
            }
        }

You can call this.Refresh(); instead of Application.DoEvents();

查看更多
爷的心禁止访问
4楼-- · 2019-06-02 06:24

You can call this.Invalidate() or this.Refresh() on the form to update it.

查看更多
登录 后发表回答