سؤال

I am using dropdownlist in asp.net, it has collection of ListItem that represents the items of the dropdownlist, each ListItem has only two fields to hold the data, Value and Text fields, but those are not enough I would like to hold more data for each item. Let's say Text1 and Text2 in additional fields, but at the same time I would like to preserve the same behavior of the DataBind() method of the dropdownlist.

هل كانت مفيدة؟

المحلول

Sure, you can use the Attributes collection:

ListItem li = new ListItem("myText", "myID");
li.Attributes.Add("data-x", "xx");
dropdown.Items.Add(li);

This will give you this HTML:

<select name="dropdown" id="dropdown">
   <option value="myID" data-x="xx">myText</option>
</select>

I suggest you prefix your custom attributes with "data-": http://html5doctor.com/html5-custom-data-attributes/

نصائح أخرى

If you want to be able to preserve the items, try setting the AppendDataBoundItems property to true. Then you can programmatically add more items:

dropDown.Items.Add("Another Item", "2");

and preserve the original ones.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top