YouTip LogoYouTip

Prop Webcontrol Listcontrol Selecteditem

## ASP.NET ListControl.SelectedItem Property The `SelectedItem` property is a core member of the ASP.NET `ListControl` class. It is used to retrieve the currently selected item from a list-bound web control. --- ## Definition and Usage The `SelectedItem` property returns the item with the lowest index among the selected items in a list control. It returns this item as a `ListItem` object, which allows you to access both its display text (`Text` property) and its underlying value (`Value` property). This property is commonly used with the following ASP.NET Web Server Controls that inherit from the `ListControl` base class: * `ListBox` * `DropDownList` * `RadioButtonList` * `CheckBoxList` --- ## Syntax ```property public virtual System.Web.UI.WebControls.ListItem SelectedItem { get; } ``` ### Return Value * **Type:** `System.Web.UI.WebControls.ListItem` * **Description:** The currently selected `ListItem` in the control. If no item is selected, it returns `null` (or `Nothing` in VB.NET). --- ## Code Example The following example demonstrates how to retrieve the text of the selected item from a `RadioButtonList` control when a user makes a selection. ```html <%@ Page Language="VB" %> ASP.NET SelectedItem Example
``` --- ## Key Considerations & Best Practices ### 1. Handling Null Values If a list control (such as a `ListBox` or `RadioButtonList`) has no default selection and the user has not selected any item, `SelectedItem` will return `null` (`Nothing` in VB.NET). Always perform a null check before accessing its properties to avoid a `NullReferenceException`: ```csharp // C# Best Practice if (myListControl.SelectedItem != null) { string selectedText = myListControl.SelectedItem.Text; string selectedValue = myListControl.SelectedItem.Value; } ``` ### 2. Multi-Selection Controls For controls that support multiple selections (such as `CheckBoxList` or a `ListBox` with `SelectionMode="Multiple"`): * `SelectedItem` will only return the **first** selected item (the one with the lowest index). * To retrieve all selected items, you must iterate through the control's `Items` collection and check the `Selected` property of each `ListItem`: ```csharp // C# Example for Multi-Selection foreach (ListItem item in myCheckBoxList.Items) { if (item.Selected) { // Process each selected item string val = item.Value; } } ``` ### 3. Difference Between SelectedItem, SelectedValue, and SelectedIndex | Property | Return Type | Description | | :--- | :--- | :--- | | **`SelectedItem`** | `ListItem` | Returns the entire selected `ListItem` object (contains both `.Text` and `.Value`). | | **`SelectedValue`** | `string` | Returns only the value of the selected item. | | **`SelectedIndex`** | `int` | Returns the zero-based index of the selected item. Returns `-1` if nothing is selected. |
← Prop Webcontrol Listcontrol SeProp Webcontrol Listcontrol Da β†’