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

21,670

Solution 1

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);

Solution 2

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);
Share:
21,670
MonsterMMORPG
Author by

MonsterMMORPG

Hello. I am the only owner and developer of web based online MMORPG game MonsterMMORPG. I am a computer engineer from Turkey and i am currently doing MA at computer engineering. I am specialized with C# &amp; ASP.net. http://www.monstermmorpg.com/ MonsterMMORPG is a Free To Play Browser Based Online Monster MMORPG Game Better Than Online Pokemon Games You will love it's awesome Monsters We have many different unique features. So i suggest you to check them out. Our game is similiar with Pokemon games but it is unique. Like diablo and torch light. You should visit following sites related to us MonsterMMORPG Facebook Pokemon Games Lovers Facebook Application MonsterMMORPG Youtube Channel Monster Game Forum Canavar Oyunu Forum Pokemon Fakemon DeviantArt MonsterMMORPG Google Plus MonsterMMORPG Twitter MonsterMMORPG Review On Browsergamez MonsterMMORPG Review On mmohuts MonsterMMORPG Developer Blog At MMORPG.com MonsterMMORPG Review On onrpg MonsterMMORPG On GameSpot MonsterMMORPG Wiki MonsterMMORPG On 1UP MonsterMMORPG Digg MonsterMMORPG Official Google Plus Page

Updated on July 09, 2022

Comments

  • MonsterMMORPG
    MonsterMMORPG almost 2 years

    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?

  • sgeddes
    sgeddes over 11 years
    Just saw this after I posted mine :-)
  • Nix
    Nix almost 11 years
    @Mounhim you are correct, aspnet.codeplex.com/workitem/7314 but that is because you can not get access to the attributes.
  • Fahad
    Fahad about 5 years
    Thanks a ton for this, exactly what I needed!