Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last option value from a DropDownList?

I have a DropDownList with the following options:

o select
1 hot
2 cold
3 warm

How can I get the last option value ("warm") from the DropDownList?

like image 458
Ayyappan Anbalagan Avatar asked Jan 23 '26 04:01

Ayyappan Anbalagan


2 Answers

Assuming that you have a variable referenced to your DropDownList:

if (myDropDownList.Items.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.

like image 123
TheQ Avatar answered Jan 24 '26 20:01

TheQ


var last = cmbMyList.Items.OfType<ListItem>().LastOrDefault();

(Thanks to Cylon Cat for correcting me)

Very Simple

like image 40
Aren Avatar answered Jan 24 '26 20:01

Aren