I have a single line textbox that is used to add numerical strings to a checked listbox. I want the listbox to auto scroll to the last item added if this is not visible to the user. I have looked for scroll properties of the listbox but I can't find anything that looks like it will scroll the listbox.
Does anyone have any advice?
Here is the code that adds an item to the listbox:
Private Sub bttAddchklstDbManagement_Click(sender As System.Object, e As System.EventArgs) Handles bttAddchklstDBmanagement.Click
If Not txtDBManagement.Text = Nothing And Not txtDBManagement.Text = "" Then
chklstDBmanagement.Items.Add(txtDBManagement.Text)
chklstDBmanagement.SetItemChecked(chklstDBmanagement.Items.Count - 1, True)
txtDBManagement.Text = Nothing
txtDBManagement.Focus()
End If
End Sub
txtDBmanagement is the TextBox
chklstDbManagement is the checked listbox
Use TopIndex after adding the item.
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add("item");
checkedListBox1.TopIndex = checkedListBox1.Items.Count - 1;
}
quite frankly i don't really like autoscrolling unless the user is at the bottom of the listbox. . . so here's what i do...
'figure out if the user is scrolled to the bottom already
Dim scrolledToBottom As Boolean = False
Dim RowsVisible As Integer = lstLog.ClientSize.Height / lstLog.ItemHeight
If lstLog.Items.Count < RowsVisible Then scrolledToBottom = True
If scrolledToBottom = False Then
If lstLog.TopIndex >= lstLog.Items.Count - RowsVisible Then
scrolledToBottom = True
End If
End If
'add your item here
lstLog.Items.Add(Now.ToString & ": " & s)
'now scroll to the bottom ONLY if the user is already scrolled to the bottom
If scrolledToBottom Then
lstLog.TopIndex = lstLog.Items.Count - 1
End If
Based on Mike's suggestion, I used a simpler & more accurate method:
lstLog.Items.Add(logText)
Dim RowsVisible As Integer = lstLog.ClientSize.Height / lstLog.ItemHeight
If ActiveControl IsNot lstLog OrElse lstLog.TopIndex >= lstLog.Items.Count - RowsVisible - 1 Then
lstLog.TopIndex = lstLog.Items.Count - 1
End If
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