C#でListViewを使用して、20件ずつデータを自動更新する方法は何ですか。

自動更新データを実現するために、タイマーを使用して、更新ごとに20件のデータだけ表示されるようにできます。以下はサンプルコードです:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ListViewAutoRefresh
{
    public partial class Form1 : Form
    {
        private Timer timer;
        private List<string> data;
        private int currentIndex;

        public Form1()
        {
            InitializeComponent();
            data = new List<string>();
            currentIndex = 0;
            timer = new Timer();
            timer.Interval = 1000; // 每秒钟刷新一次
            timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            // 每次刷新显示20条数据
            int count = Math.Min(20, data.Count - currentIndex);
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    string item = data[currentIndex++];
                    listView1.Items.Add(item);
                }
            }
            else
            {
                timer.Stop();
            }
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            // 模拟生成一些数据
            for (int i = 0; i < 100; i++)
            {
                data.Add($"Item {i}");
            }

            timer.Start();
        }
    }
}

この例では、「開始」ボタンをクリックすると、データがいくつか生成され、タイマーが開始されます。タイマーは毎秒Timer_Tickイベントをトリガーし、listView1に20件のデータを追加します。すべてのデータが表示されると、タイマーは停止します。

Windowsフォームには、ListViewコントロール(名前:listView1)とButtonコントロール(名前:buttonStart)を追加する必要があります。そして、buttonStartのClickイベントをbuttonStart_Clickメソッドにバインドしてください。

このコードは単なるサンプルであり、お客様の具体的な要件に合わせて調整が必要です。

bannerAds