System.Web.UI.WebControls Namespace DataList Class
Sets or retrieves the index of the selected item in a DataList control.
Script |
DataList.SelectedIndex [ = intIndex ] |
This property can only be used programmatically; it cannot be set when declaring the control.
intIndex |
Integer specifying the ordinal index of the selected item. |
The property is read/write with no default value.
Exception Type |
Condition |
ArgumentOutOfRangeException |
The given index is set to less than -1 or greater than or equal to the items count of the list. |
Items in a DataList are indexed in the order in which they are defined in the data source, starting with an index of zero.
The SelectedIndex property is mainly used to programmatically specify or determine the index of the selected item in a DataList. This index can then be used to access the methods and properties of the selected item.
SelectedIndex returns a value of -1 if no item is selected. Always provide code to test this value before attempting to reference any selected item in your code. You can programmatically deselect an item by setting the SelectedIndex property to -1.
NOTE: Like most indexes in ASP.NET, SelectedIndex is zero-based, meaning the first item in the collection returns an index of 0.
The following example demonstrates using the SelectedIndex property to determine the selected item in a DataList control.
void myListSelectHandler ( Object src, EventArgs e ) {
string title = myList.DataKeys [ myList.SelectedIndex ].ToString ( );
string query = "Select * FROM pubs_Titles where Title_id = '" + title + "'";
myDetailsList.DataSource = fetchData ( query, "pubs" );
myDetailsList.DataBind ( );
}
Sub myListSelectHandler ( src As Object, e As EventArgs )
Dim title As String = myList.DataKeys ( myList.SelectedIndex ).ToString ( )
Dim query As String = "Select * FROM pubs_Titles where Title_id = '" + title + "'"
myDetailsList.DataSource = fetchData ( query, "pubs" )
myDetailsList.DataBind ( )
End Sub |
|
C# |
VB |
Show me
DataList Members SelectedIndexChanged SelectedItem SelectedItemTemplate SelectedItemStyle Allowing Users to Select Items in a DataList Control