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.