YouTip LogoYouTip

Prop Webcontrol Listbox Selectionmode

# ASP.NET WebControl: ListBox SelectionMode Property The `SelectionMode` property is a key feature of the ASP.NET WebControl `ListBox` class. It determines how users can interact with and select items within the list box control. --- ## Definition and Usage The `SelectionMode` property gets or sets the selection mode of the `ListBox` control. This property allows developers to specify whether a user can select only a single item or multiple items from the list box at one time. --- ## Syntax ```xml ``` ### Property Values | Property Value | Description | | :--- | :--- | | **`Single`** | **Default.** The user can select only one item at a time from the `ListBox`. | | **`Multiple`** | The user can select multiple items simultaneously. Users can perform multi-selection by holding down the `Ctrl` or `Shift` keys while clicking. | --- ## Code Examples ### Example 1: Basic Declarative Markup The following example demonstrates how to declare a `ListBox` with `SelectionMode` set to `Multiple` in your `.aspx` page: ```xml
Apple Banana Cherry Date
``` ### Example 2: Handling Multiple Selections in Code-Behind (C#) When `SelectionMode` is set to `Multiple`, you need to iterate through the items in the code-behind to determine which options the user selected. **ASPX Markup:** ```xml
Apple Banana Cherry



``` **C# Code-Behind (`.aspx.cs`):** ```csharp protected void btnSubmit_Click(object sender, EventArgs e) { string selectedItems = "You selected: "; bool itemSelected = false; // Loop through each item in the ListBox foreach (ListItem item in lbFruits.Items) { if (item.Selected) { selectedItems += item.Text + ", "; itemSelected = true; } } if (itemSelected) { // Trim the trailing comma and space lblResult.Text = selectedItems.TrimEnd(',', ' '); } else { lblResult.Text = "Please select at least one item."; } } ``` --- ## Key Considerations 1. **Retrieving Selected Values:** * When `SelectionMode` is set to `Single`, you can easily retrieve the selected item using `ListBox.SelectedValue` or `ListBox.SelectedItem`. * When `SelectionMode` is set to `Multiple`, `ListBox.SelectedValue` will only return the value of the *first* selected item. To retrieve all selected items, you must iterate through the `ListBox.Items` collection and check the `Selected` property of each `ListItem` (as shown in Example 2). 2. **User Experience (UX):** * When using `SelectionMode="Multiple"`, it is highly recommended to provide a brief instruction (e.g., *"Hold Ctrl to select multiple items"*) since standard HTML multi-select boxes can sometimes be unintuitive for non-technical users.
← Python MultithreadingProp Webcontrol Listbox Rows β†’