Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attribute from DropdownList SelectedItem

I have a dropdownlist where I need to store more data than the standard list item allows. The approach I've taken is to add an attribute to each of the listitems.

I monitor for changes and can return the SelectedIndex, but I'm not sure how to get the attribute back from there, or whether there are any easier ways of achieving this.

Any ideas?

like image 290
dotnetnoob Avatar asked Feb 12 '13 11:02

dotnetnoob


2 Answers

Try this:

ddl.SelectedItem.Attributes["key"];
like image 181
banana Avatar answered Oct 09 '22 05:10

banana


I did try this once before and i figured i could not really use the attribute's on the DropDownList attributes.

What i did was the following:

Create a list containing a KeyValuePair. The Key in the KeyValuePair is the same ID as you put in your DropDownList Item.

The value of the KeyValuePair, is the value (or values) that you would like to keep/connect with your item.

You can store the List in your viewState and read the data once you have selected an item in your DropDownList and find the right KeyValuePair using the ID.

So you can "store" the data like this:

    var listKeyValuePair = new List<KeyValuePair<int, string>>();
    listKeyValuePair.Add(new KeyValuePair<int, string>(1, "data"));
    ViewState["DataList"] = listKeyValuePair;

And you can get your data like this:

    var listKeyValuePair = (List<KeyValuePair<int, string>>)ViewState["DataList"];
    var dataILikeToHave = listKeyValuePair.Find(k => k.Key == Convert.ToInt16(dropDownlist.SelectedItem.Value));
like image 31
vanSanten Avatar answered Oct 09 '22 05:10

vanSanten