C# listbox设置自动滚动
时间: 2023-11-23 18:52:54 浏览: 72
在C#中,我们可以使用listbox控件来显示一系列的记录。当记录数量超过listbox控件的可见范围时,我们需要设置自动滚动以便查看所有的记录。以下是三种常用的方法来实现自动滚动:
1.方法1:添加记录后,选择最后一条记录,让滚动条滚动到底部,再自动取消选中行。
```
listBox1.Items.Add(t + ":a good day");listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.SelectedIndex = -1; //是否取消选中行
```
2.方法2:通过计算显示行数,设置TopIndex属性,实现滚动目的。
```
listBox1.Items.Add(t + ":a good day");
listBox1.TopIndex = listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight);
```
3.方法3:先计算滚动条是否在底部,然后添加记录,根据需要确定是否自动滚动。
```
bool scoll =false;
if (listBox1.TopIndex == listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight))
scoll = true;
listBox1.Items.Add(t + ":a good day");
if(scoll)
listBox1.TopIndex = listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight);
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)