C#ListBox使用介绍

1 自动滚动到底部方法

方法一:

1
2
3
this.listBox1.Items.Add("new line");
this.listBox1.SelectedIndex = this.listBox1.Items.Count - 1;
this.listBox1.SelectedIndex = -1;

在添加记录后,先选择最后一条记录,滚动条会自动到底部,再取消选择。
缺点是需两次设置选中条目,中间可能会出现反色的动画,影响美观。

方法二:

1
2
this.listBox1.Items.Add("new line");
this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);

通过计算ListBox显示的行数,设置TopIndex属性(ListBox中第一个可见项的索引)而达到目的。

方法三:智能滚动

1
2
3
4
5
6
bool scroll = false;
if(this.listBox1.TopIndex == this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight))
scroll = true;
this.listBox1.Items.Add("new line");
if (scroll)
this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);

在添加新记录前,先计算滚动条是否在底部,从而决定添加后是否自动滚动。既可以在需要时实现自动滚动,又不会在频繁添加记录时干扰用户对滚动条的控制。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值