Asp.net C # ListBox auto-scroll to bottom method summary

Source: Internet
Author: User

After a record (ListBox. Items. Add method) is added to ListBox, the scroll bar automatically returns to the top. We may want it to automatically scroll to the bottom. This article briefly introduces several methods.

Method 1:

The Code is as follows: Copy code

This. listBox1.Items. Add ("new line ");

This. listBox1.SelectedIndex = this. listBox1.Items. Count-1;

This. listBox1.SelectedIndex =-1;

After adding a record, select the last record. the scroll bar automatically goes to the bottom and then deselect the selection.

The disadvantage is that you need to set the selected entries twice, and there may be a reversed animation in the middle, affecting the appearance.

Method 2:

The Code is as follows: Copy code

This. listBox1.Items. Add ("new line ");

This. listBox1.TopIndex = this. listBox1.Items. Count-(int) (this. listBox1.Height/this. listBox1.ItemHeight );

You can set the TopIndex attribute (index of the first visible item in ListBox) by calculating the number of lines displayed in ListBox.

Method 2 plus: intelligent Rolling

The Code is as follows: Copy code

Bool scroll = false;

If (this. listBox1.TopIndex = this. listBox1.Items. Count-(int) (this. listBox1.Height/this. listBox1.ItemHeight ))

Scroll = true;

This. listBox1.Items. Add ("new line ");

If (scroll)

This. listBox1.TopIndex = this. listBox1.Items. Count-(int) (this. listBox1.Height/this. listBox1.ItemHeight );

Before adding a new record, calculate whether the scroll bar is at the bottom to determine whether to automatically scroll after the new record is added.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.