.net 如何滚动列表框以查看事件中添加的最后一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15527339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to a scroll a listbox to see the last item added, on event
提问by Pezzzz
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
txtDBmanagement 是文本框
chklstDbManagement 是选中的列表框
回答by albert
Use TopIndex after adding the item.
添加项目后使用 TopIndex。
private void button1_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add("item");
checkedListBox1.TopIndex = checkedListBox1.Items.Count - 1;
}
回答by Mike A.
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
回答by Ahmed Abdelhameed
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

