Prop Webcontrol Dropdownlist Selectedindex
## ASP.NET DropDownList SelectedIndex Property
The `SelectedIndex` property is a core member of the ASP.NET `DropDownList` Web Server Control. It is used to get or set the zero-based index of the currently selected item in the dropdown list.
---
## Definition and Usage
The `SelectedIndex` property serves two primary purposes:
* **Get:** Retrieves the index of the currently selected item. The index is zero-based, meaning the first item in the list has an index of `0`, the second has `1`, and so on. If no item is selected, it returns `-1`.
* **Set:** Programmatically selects an item in the dropdown list by specifying its index.
---
## Syntax
```syntax
```
Or in your code-behind (C# / VB.NET):
```csharp
// C# - Get the selected index
int index = myDropDownList.SelectedIndex;
// C# - Set the selected index
myDropDownList.SelectedIndex = 2; // Selects the third item
```
```vb
' VB.NET - Get the selected index
Dim index As Integer = myDropDownList.SelectedIndex
' VB.NET - Set the selected index
myDropDownList.SelectedIndex = 2 ' Selects the third item
```
---
## Code Example
The following example demonstrates how to retrieve the selected item's text when a user clicks a button.
### ASPX Page (Markup and Inline Code)
```html
<%@ Page Language="VB" %>
DropDownList SelectedIndex Example
```
---
## Key Considerations
1. **Zero-Based Indexing:** Always remember that the index starts at `0`. If your `DropDownList` has 5 items, the valid range for `SelectedIndex` is `0` to `4`.
2. **Default Selection:** By default, if you do not explicitly set the `SelectedIndex` or set a `Selected` attribute on a `ListItem`, the `SelectedIndex` defaults to `0` (the first item in the list).
3. **Clearing Selection:** Setting `SelectedIndex` to `-1` clears the selection, meaning no item will be selected.
4. **Out of Range Exception:** If you attempt to set the `SelectedIndex` to a value greater than or equal to the number of items in the list (e.g., setting it to `5` when there are only 3 items), ASP.NET will throw an `ArgumentOutOfRangeException`.
YouTip