【问题标题】:How to a scroll a listbox to see the last item added, on event如何滚动列表框以查看最后添加的项目,事件
【发布时间】:2013-03-20 15:07:31
【问题描述】:

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

有人有什么建议吗?

以下是向列表框中添加项目的代码:

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

【问题讨论】:

    标签: .net vb.net winforms


    【解决方案1】:

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

        '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
    

    【讨论】:

      【解决方案2】:

      根据 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
      

      【讨论】:

        【解决方案3】:

        添加项目后使用 TopIndex。

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

        【讨论】:

          猜你喜欢
          • 2021-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多