views:

114

answers:

3

consider my dropdownlist has,

o select
1 hot
2 cold
3 warm

i want to get warm (ie)get last option value of a dropdownlist using c#?

+5  A: 

Assuming that you have a variable referenced to your DropDownList:

if (myDropDownList.Count > 0)
{
    string myValue = myDropDownList.Items[myDropDownList.Items.Count - 1].Value;
}

Note that you should probably check that the DropDownList has items first, or else this will throw an IndexOutOfBounds exception when the list is empty. Thanks @Cylon.

JN Web
Check for an empty list first?
Cylon Cat
Edited to reflect that, thanks for the heads up :)
JN Web
A: 

Something like cboTemp.SelectedIndex = cboTemp.Items.Count -1;

Raj
+1  A: 
var last = cmbMyList.Items.OfType<ListItem>().LastOrDefault();

(Thanks to Cylon Cat for correcting me)

Very Simple

Aren
var last = cmbMyList.Items.OfType<ListItem>().LastOrDefault(); // the ListItemCollection isn't generic; you have to make a generic collection before you can use LINQ functions onit.
Cylon Cat
Ah yes! You're correct!
Aren