6

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

有人有建议吗?

这是将项目添加到列表框的代码:

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 是 TextBox
chklstDbManagement 是选中的列表框

4

3 回答 3

19

添加项目后使用 TopIndex。

    private void button1_Click(object sender, EventArgs e)
    {
        checkedListBox1.Items.Add("item");
        checkedListBox1.TopIndex = checkedListBox1.Items.Count - 1;
    }
于 2013-03-20T15:31:31.140 回答
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
于 2013-12-13T15:47:07.720 回答
1

根据 Mike 的建议,我使用了一种更简单、更准确的方法:

    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
于 2016-10-18T14:46:39.053 回答