我有一个单行文本框,用于将数字字符串添加到选中的列表框中。我希望列表框自动滚动到最后添加的项目,如果这对用户不可见。我已经查找了列表框的滚动属性,但我找不到任何看起来会滚动列表框的内容。
有人有任何建议吗?
以下是将项目添加到列表框的代码:
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是选中的列表框
答案 0 :(得分:18)
添加项目后使用TopIndex。
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add("item");
checkedListBox1.TopIndex = checkedListBox1.Items.Count - 1;
}
答案 1 :(得分: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
答案 2 :(得分:1)
根据Mike的建议,我使用了一个更简单的&amp;更准确的方法:
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