Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to a scroll a listbox to see the last item added, on event

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

like image 346
Pezzzz Avatar asked Mar 20 '13 15:03

Pezzzz


3 Answers

Use TopIndex after adding the item.

    private void button1_Click(object sender, EventArgs e)
    {
        checkedListBox1.Items.Add("item");
        checkedListBox1.TopIndex = checkedListBox1.Items.Count - 1;
    }
like image 78
albert Avatar answered Oct 23 '22 05:10

albert


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
like image 11
Mike A. Avatar answered Oct 23 '22 07:10

Mike A.


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
like image 2
41686d6564 stands w. Palestine Avatar answered Oct 23 '22 06:10

41686d6564 stands w. Palestine