Furkan Gözükara
Furkan Gözükara

Reputation: 23800

How can i add extra attribute fields to the asp.net dropdown list

Below I am able to set values and the text:

dropListUserImages.DataValueField = "Value";
dropListUserImages.DataTextField = "Text";
dropListUserImages.Items.Add(new ListItem { Text = srText, Value = srValue});

I also want to set extra attributes such as:

data-imagesrc
data-description 

How can I do that?

Upvotes: 13

Views: 24745

Answers (2)

David Rogers
David Rogers

Reputation: 2643

I've had the same challenge with translating complex lists of object into values that can be read on the front end, I've used logic similar to the below and found it very useful because it can be adaptive for every type of object:

//Object can be whichever type as you wish
List<Object> example = new List<Object>();

var listItemExamples = example
    .Select(a => new Func<ListItem>(() => {
                ListItem item = new ListItem(a.PropropertyA.ToString(), a.PropropertyB.ToString() );
                item.Attributes["data-PropropertyC"] = a.PropropertyC.ToString();
                return item;
            })())
    .ToArray();

dropListUserImages.Items.AddRange(listItemExamples);

Upvotes: 2

Nix
Nix

Reputation: 58522

Use:

ListItem test  = new ListItem { Text = srText, Value = srValue}
test.Attributes.Add("data-imagesrc", "xxx");
test.Attributes.Add("data-description", "xxx");
dropListUserImages.Items.Add(test);

Upvotes: 22

Related Questions