本文目录导读:
在C# Windows窗体应用程序中,ListBox(列表框)是一个经典且功能丰富的控件,用于展示和管理一组可选择的列表项,无论是简单的数据展示,还是复杂的交互逻辑(如动态加载、多选操作或数据绑定),ListBox都扮演着重要角色,本文将从基础用法入手,逐步探讨ListBox的高级功能,并结合实际代码示例,帮助开发者全面掌握这一控件的核心技术。
在Visual Studio中,通过拖拽工具箱中的ListBox控件到窗体上即可快速创建一个列表框,初始化时,可以通过代码动态添加项:
// 添加单个项
listBox1.Items.Add("第一项");
listBox1.Items.Add("第二项");
// 添加集合
string[] items = { "苹果", "香蕉", "橘子" };
listBox1.Items.AddRange(items);
常用事件包括:
通过按钮操作ListBox的增删功能:
// 添加项
private void btnAdd_Click(object sender, EventArgs e) {
if (!string.IsNullOrEmpty(txtInput.Text)) {
listBox1.Items.Add(txtInput.Text);
txtInput.Clear();
}
}
// 删除选中项
private void btnRemove_Click(object sender, EventArgs e) {
if (listBox1.SelectedIndex != -1) {
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
}
ListBox支持直接绑定数据集合(如List、数组、DataTable等),通过DataSource
属性实现:
List<string> fruits = new List<string> { "苹果", "香蕉", "橘子" };
listBox1.DataSource = fruits;
对于复杂对象,可以指定显示字段:
public class Product {
public string Name { get; set; }
public int Price { get; set; }
}
List<Product> products = new List<Product> {
new Product { Name = "手机", Price = 2000 },
new Product { Name = "电脑", Price = 5000 }
};
listBox1.DisplayMember = "Name"; // 显示Name属性
listBox1.ValueMember = "Price"; // 实际值对应Price
当数据源变更时,需重新绑定:
products.Add(new Product { Name = "平板", Price = 3000 });
listBox1.DataSource = null; // 清空原有绑定
listBox1.DataSource = products;
将SelectionMode
设为MultiExtended
,允许用户通过Ctrl或Shift键多选:
listBox1.SelectionMode = SelectionMode.MultiExtended;
// 获取所有选中项
foreach (var item in listBox1.SelectedItems) {
MessageBox.Show(item.ToString());
}
通过DrawMode
属性实现自定义绘制:
listBox1.DrawMode = DrawMode.OwnerDrawVariable;
listBox1.MeasureItem += ListBox1_MeasureItem;
listBox1.DrawItem += ListBox1_DrawItem;
private void ListBox1_MeasureItem(object sender, MeasureItemEventArgs e) {
e.ItemHeight = 30; // 设置项高度
}
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) {
e.DrawBackground();
if (e.Index >= 0) {
// 绘制文本和图标
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),
new Font("宋体", 10),
Brushes.Black,
new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
}
}
当列表项数量极大时(如超过10万条),启用虚拟模式可显著提升性能:
listBox1.VirtualMode = true;
listBox1.RetrieveVirtualItem += ListBox1_RetrieveVirtualItem;
private void ListBox1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e) {
e.Item = new ListBoxItem($"第{e.ItemIndex}项");
}
DisplayMember
或数据源未实现IList
接口。BeginUpdate()
和EndUpdate()
批量操作:listBox1.BeginUpdate();
for (int i = 0; i < 1000; i++) {
listBox1.Items.Add("项" + i);
}
listBox1.EndUpdate();
在异步操作中,需通过Invoke
方法更新UI:
this.Invoke(new Action(() => {
listBox1.Items.Add("新项");
}));
随着互联网的普及和信息技术的飞速发展台湾vps云服务器邮件,电子邮件已经成为企业和个人日常沟通的重要工具。然而,传统的邮件服务在安全性、稳定性和可扩展性方面存在一定的局限性。为台湾vps云服务器邮件了满足用户对高效、安全、稳定的邮件服务的需求,台湾VPS云服务器邮件服务应运而生。本文将对台湾VPS云服务器邮件服务进行详细介绍,分析其优势和应用案例,并为用户提供如何选择合适的台湾VPS云服务器邮件服务的参考建议。
工作时间:8:00-18:00
电子邮件
1968656499@qq.com
扫码二维码
获取最新动态