Automatically scroll the listview from top to bottom in c#

点点圈 提交于 2021-01-28 09:55:48

问题


Good day guys.

I am currently creating a some kind of advertisement app. It is simple text scrolling from top to bottom and will repeat again. I am currently using listview to do this in c#. The texts that will show in the listview will be coming from a database. I am using the timer to automatically refresh the form. The problem is how can I move it or scroll it from top to bottom automatically every time the form loads and will repeat again every time it finished.

Thank you.

This is the code so far as requested by Mr. King King.

 private void timer1_Tick(object sender, EventArgs e)
    {
        this.Refresh();
        listView1.TopItem = listView1.Items.Cast<ListViewItem>().LastOrDefault();
    }

回答1:


You can set the ListView.TopItem to the last item and it should ensure the scrollbar to be at the bottom:

listView1.TopItem = listView1.Items[listView1.Items.Count-1];

You should be sure your listView1 has at least 1 item, here is a LINQ version which is safer:

listView1.TopItem = listView1.Items.Cast<ListViewItem>().LastOrDefault();

UPDATE

If you want to scroll from top to bottom by each item, try this:

int lastIndex;
private void timer1_Tick(object sender, EventArgs e)
{
    this.Refresh();
    int i = listView1.TopItem == null ? -1 : listView1.TopItem.Index;        
    if(i>-1) {
      if(i == lastIndex || i == listView1.Items.Count - 2) i = 0;
      lastIndex = i;
      listView1.TopItem = listView1.Items[++i];
    }
}



回答2:


After adding an item:

listView.EnsureVisible(listView.Items.Count - 1);


来源:https://stackoverflow.com/questions/20209689/automatically-scroll-the-listview-from-top-to-bottom-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!