1.ListBox
在WinForms中,ListBox是一种常用的控件,用于显示项目列表。你可以通过Visual Studio或者手动创建一个ListBox,并对其进行操作。
Visual Studio中创建ListBox:
-
使用Visual Studio创建ListBox:
- 打开Visual Studio并创建一个新的WinForms应用程序项目。
- 打开窗体设计器,从工具箱中拖拽ListBox控件到窗体上。
-
常用属性和方法:
- Items:这个属性代表了ListBox中的项目集合。
- SelectionMode:可以设置选择模式,如单选或多选。
- SelectedIndex:用于获取或设置当前选择项目的索引。
- SelectedItems:表示被选中的项目的集合。
- 添加项目:通过
Items.Add()
方法向ListBox中添加项目。 - 移除项目:通过
Items.Remove()
方法或Items.RemoveAt()
方法移除项目。
下面是一个简单的示例代码,演示了如何使用ListBox控件:
using System;
using System.Windows.Forms;namespace ListBoxExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}private void btnAdd_Click(object sender, EventArgs e)
{
// 向ListBox中添加项目
listBoxItems.Items.Add(txtNewItem.Text);
txtNewItem.Clear();
}private void btnRemove_Click(object sender, EventArgs e)
{
// 移除选中的项目
if (listBoxItems.SelectedIndex != -1)
{
listBoxItems.Items.RemoveAt(listBoxItems.SelectedIndex);
}
}private void btnClear_Click(object sender, EventArgs e)
{
// 清空ListBox中的所有项目
listBoxItems.Items.Clear();
}private void btnSelectedItems_Click(object sender, EventArgs e)
{
// 获取选中的项目
string selectedItems = "";
foreach (var item in listBoxItems.SelectedItems)
{ <