RSS

Search Engine

Thursday, May 20, 2010

ASP.Net ListBox SelectedIndex Property

The SelectedIndex property of ASP.Net ListBox control enables you to get or set the zero-based index of the selected list item dynamically using C# code. When user clicks on any list item of listbox control it fires the SelectedIndexChanged event that can be handled at server side to get the index of the list item clicked by the user. There you can use the SelectedIndex property that returns the integer type value associated to the list item selected by the user. It also allows you to set the list item at the specified index in selected state programmatically. Using SelectedIndex property in the C# code you can also access the properties of Items collection property of listbox control. Following are the properties of Items collection that can be accessed using SelectedIndex property of listbox control:

1. Attributes: it allows you to add the attributes to the associated list item dynamically.

2. Enabled: it allows you to enable or disable the selection of list item based on its Boolean type true/false value.

3. Selected: it sets the list item in selected state based on its true or false Boolean value.

4. Text: it allows you to get or set the text content of the selected list item of listbox control.

5. Value: it allows you to get or set the value of selected list item dynamically.

As SelectedIndex property is an integer type property, you can specify the integer type value to set the list item of listbox control in selected state. If you will specify the integer value more than the maximum index of listbox control items then it will throw an error: "System.ArgumentOutOfRangeException: 'ListBox1' has a SelectedIndex which is invalid because it does not exist in the list of items. Parameter name: value". Before specifying the value for SelectedIndex property you must ensure that it must be greater than or equal to 0 and less than the maximum index number of listbox control. By default the SelectedIndex property has value -1 that represents the un-selected state of all the list items of listbox.

You can use the following code to get the SelectedIndex of list item of listbox control selected by the user:

Response.Write(ListBox1.SelectedIndex);

Similarly you can assign the integer value to the SelectedIndex property to select the list item programmatically:

ListBox1.SelectedIndex = 3;

For accessing the properties of Items collection property associated to the selected list item using SelectedIndex property you can use the following

C# code:

Response.Write(ListBox1.Items[ListBox1.SelectedIndex].Value);

Similarly you can get or set the values for different properties of Items property of listbox control as we discussed earlier in this tutorial such as Attributes, Enabled, Selected, Text and Value.

0 comments:

Post a Comment