Prop Webcontrol Listcontrol Selectedvalue
## ASP.NET ListControl.SelectedValue Property
The `SelectedValue` property is a core member of the `ListControl` class in ASP.NET. It is used to get or set the value of the selected item in a list control.
---
## Definition and Usage
The `SelectedValue` property represents the value of the currently selected `ListItem` within a list control (such as `ListBox`, `DropDownList`, `RadioButtonList`, or `CheckBoxList`).
* **Getting the value:** It returns the `Value` property of the selected `ListItem`. If no item is selected, it returns an empty string (`""`).
* **Setting the value:** It selects the `ListItem` in the control that matches the specified value. If no item matches the specified value, an `ArgumentOutOfRangeException` is thrown.
---
## Syntax
```syntax
public virtual string SelectedValue { get; set; }
```
### Property Value
* **Type:** `System.String`
* **Description:** The value of the selected item in the list control. The default is an empty string (`""`).
---
## Code Examples
### Example 1: Basic Usage with RadioButtonList (VB.NET)
The following example demonstrates how to retrieve the value of the selected item in a `RadioButtonList` control when the selection changes.
```asp
```
### Example 2: Programmatically Setting the Selected Value (C#)
You can also use the `SelectedValue` property to programmatically select an item in the list.
```asp
```
---
## Key Considerations
### 1. Difference Between `SelectedValue`, `SelectedIndex`, and `SelectedItem`
When working with list controls, it is important to understand the differences between these three properties:
| Property | Return Type | Description |
| :--- | :--- | :--- |
| **`SelectedValue`** | `String` | Gets or sets the **value** attribute of the selected item. |
| **`SelectedIndex`** | `Int32` | Gets or sets the zero-based **index** of the selected item. |
| **`SelectedItem`** | `ListItem` | Gets the actual **`ListItem` object** that is selected, allowing access to both its `Text` and `Value` properties. |
### 2. Exception Handling when Setting `SelectedValue`
If you attempt to set `SelectedValue` to a value that does not exist in the control's item list, ASP.NET will throw an `ArgumentOutOfRangeException`.
To prevent this, you can verify if the item exists before setting it:
```csharp
string targetValue = "Item 4";
ListItem item = ddlOptions.Items.FindByValue(targetValue);
if (item != null)
{
ddlOptions.SelectedValue = targetValue;
}
else
{
// Handle the case where the value does not exist
}
```
### 3. Behavior with Multiple Selection Controls
For controls that support multiple selections (such as `ListBox` in multiple mode or `CheckBoxList`):
* **Getting `SelectedValue`** will only return the value of the *first* selected item with the lowest index.
* To retrieve all selected values, you must iterate through the `Items` collection and check the `Selected` property of each `ListItem`.
YouTip