Intermediate
10 min read
Control #11
ListBox Control
The ListBox displays a scrollable list of items. Users can select one or more items.
What is a ListBox?
A ListBox shows items in a list. Users can scroll through and select items. It's great for showing a list of options, files, or names.
Code Example
// Add items
listBox1.Items.Add("Item 1");
listBox1.Items.AddRange(new object[] { "Item 2", "Item 3" });
// Get selected item
private void btnGetSelected_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
MessageBox.Show($"Selected: {listBox1.SelectedItem}");
}
}
// Multi-selection
listBox1.SelectionMode = SelectionMode.MultiExtended;
// Get all selected items
private void btnGetAllSelected_Click(object sender, EventArgs e)
{
var selected = new List<string>();
foreach (var item in listBox1.SelectedItems)
{
selected.Add(item.ToString());
}
MessageBox.Show($"Selected: {string.Join(", ", selected)}");
}
Exercise
Task: Create a simple shopping list app.
- Add a ListBox with shopping items.
- Add a TextBox and Button to add new items.
- Add a Button to remove selected items.
- Add a Button to clear all items.
- Add a Label showing total items count.
Key Takeaway
ListBox is great for displaying lists. Use SelectionMode to control
whether users can select one or multiple items.