Setting a custom attribute in a list item in an HTML Select control (.NET / C #)

I am trying to create a custom attribute for each list item in an HTML HTML control file.

The HTML result should look something like this:

<select> <option value="1" data-value="myValue1">item</option> <option value="2" data-value="myValue2">item</option> <option value="3" data-value="myValue3">item</option> </select> 

I tried adding such attributes, but they do not appear:

 <select id="selectList" class="multiselect" multiple="true" name="selectList[]" runat="server"></select> 


 ListItemCollection values = new ListItemCollection(); ListItem test = new ListItem("add"); test.Attributes.Add("data-value", "myValue"); values.Add(test); this.selectList.DataSource = values; this.selectList.DataBind(); 

Any thoughts on how this can be achieved? Thanks!

+7
source share
1 answer

You need to add attributes to manage list items. When data is bound, the list control can set only the name and text. The easiest way is to add items manually instead of data binding - for example:

 ListItem test = new ListItem("text1", "value1"); test.Attributes.Add("data-value", "myValue1"); applicationList.Items.Add(test); 

If you must use data binding, you need to handle the DataBound event, and then iterate over the controls and add / set the required attribute. Honestly, I found that this is a round-the-clock way of doing things.

+12
source

All Articles