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.