C# ListBox: Usage and Operations Guide

In C#, a ListBox is a control that can display a group of items. It allows users to select one or more items and has the ability to display text, images, or custom data.

When using a ListBox, you can perform the following actions:

  1. To add items: You can add items to a ListBox using the Items property. For example, you can use the Items.Add() method to add a new item to the ListBox. You can also use the Items.AddRange() method to add multiple items at once.
listBox1.Items.Add("Item 1");
listBox1.Items.Add("Item 2");
listBox1.Items.AddRange(new object[] { "Item 3", "Item 4", "Item 5" });
  1. To delete items: You can use the Items property of a ListBox to remove items. For example, you can use the Items.Remove() method to delete a specified item. You can also use the Items.RemoveAt() method to delete an item based on its index.
listBox1.Items.Remove("Item 1");
listBox1.Items.RemoveAt(0);
  1. Clear items: You can use the Items property of a ListBox to clear all items. For example, you can use the Items.Clear() method to clear all items.
listBox1.Items.Clear();
  1. To retrieve the selected items: You can use the SelectedItems property of the ListBox to obtain the selected items. This property returns a collection that can be iterated through using a foreach loop.
foreach (var item in listBox1.SelectedItems)
{
    // 处理选中的项
}
  1. Single choice mode, only one option can be selected.
  2. Multiple selection mode allows you to choose more than one option, but you cannot select consecutive options.
  3. MultiExtended: Multiple selection mode, allows choosing multiple items and selecting consecutive multiple items.
listBox1.SelectionMode = SelectionMode.One; // 设置为单选模式
listBox1.SelectionMode = SelectionMode.MultiSimple; // 设置为多选模式,但不能选择连续的多项
listBox1.SelectionMode = SelectionMode.MultiExtended; // 设置为多选模式,可以选择连续的多项

These are some common uses of the ListBox. Depending on specific needs, other properties and methods can also be used to enhance its functionality.

bannerAds