如何滚动列表框以查看事件中添加的最后一项

Pez*_*zzz 5 .net vb.net winforms

我有一个单行文本框,用于将数字字符串添加到选中的列表框.我希望列表框自动滚动到最后添加的项目,如果这对用户不可见.我已经查找了列表框的滚动属性,但我找不到任何看起来会滚动列表框的内容.

有人有建议吗?

以下是将项添加到列表框的代码:

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
Run Code Online (Sandbox Code Playgroud)

txtDBmanagement是TextBox
chklstDbManagement是选中的列表框

alb*_*ert 18

添加项目后使用TopIndex.

    private void button1_Click(object sender, EventArgs e)
    {
        checkedListBox1.Items.Add("item");
        checkedListBox1.TopIndex = checkedListBox1.Items.Count - 1;
    }
Run Code Online (Sandbox Code Playgroud)


小智 10

坦率地说,我不喜欢自动滚动,除非用户位于列表框的底部...所以这就是我做的......

    '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
Run Code Online (Sandbox Code Playgroud)