C#设置listbox行数
时间: 2023-10-19 09:26:31 浏览: 57
在C#中,可以使用多种方法设置ListBox的行数。以下是三种常用的方法:
方法1:添加记录后,选择最后一条记录,让滚动条滚动到底部,再自动取消选择:
```csharp
listBox1.Items.Add("a good day");
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.SelectedIndex = -1; //取消选择行
```
方法2:通过计算显示行数,设置TopIndex属性,实现滚动目的:
```csharp
listBox1.Items.Add("a good day");
listBox1.TopIndex = listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight);
```
方法3:先计算滚动条是否在底部,然后添加记录,根据需要确定是否自动滚动:
```csharp
bool scroll = false;
if (listBox1.TopIndex == listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight))
scroll = true;
listBox1.Items.Add("a good day");
if (scroll)
listBox1.TopIndex = listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight);
```
以上是三种常用的方法,你可以根据需要选择其中一种来设置ListBox的行数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [C# ListBox自动滚动方法](https://blog.csdn.net/qq_27474555/article/details/132141212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]