I am adding items to a c# list box and want to always scroll it to the last item added to the list so it is visible. The list will usually exceed the space available so the vertical scroll bar will display and as users can move this I need to force it jump to the end again with a new item. The only useful way I have found is to use the TopIndex property with the rows in box - number of row that can be displayed. I have this working OK with the code below unless one of the lines was too long in which case the horizontal scroll bar uses up the room for about the last 2 items. If I could figure out if the horizontal bar was displayed I could change the number of rows in the computation to account for it.
LB1.Items.Add(strText);
LB1.TopIndex = Math.Max(0,lbXmlMsg.Items.Count - 10); // 10 rows visible
This seems like a lot of work to just make sure that a new item is visible. Am I missing something ovvious here ?
You can check if the horizontal scrollbar is visible by calling
LB1.HorizontalScrollbar
As per the OP's comment, the above does not work.
I would also say that hard coded numbers are bad practice, you can do something like this: How to scroll to bottom of ListBox?
And then there is this as a way to autoscroll http://www.csharp-examples.net/autoscroll/
I haven't tried any of these but they should work.
If you swap to a ListView this has an EnsureVisible function that does exactly the job you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With