Search code examples
c#asp.netdropdownlistitem

How do I add a css class when using new ListItem on databound?


I am adding some values to a drop down list using a loop:

for (Int32 i = 1; i <= MaxOrderQuantity; i++)
{
    myDropDownList.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)));
}

I want to add a CSS attribute to the new ListItem at the same time. I have seen I can use

.Attributes.Add("class","foo")

However the only way I can find to do it is by breaking down my single line of code in to 3 separate lines of code like this:

ListItem newListItem = new ListItem("my value", "my value");
newListItem.Attributes.Add("class", "blah");
myDropDownList.Items.Add(newListItem);

The intellisense allowed me to write the following code but it errors and says "The best overloaded method match for 'System.Web.UI.WebControls.ListItemCollection.Add(string)' has some invalid arguments.

myDropDownList.Items.Add(new ListItem(Convert.ToString(i), Convert.ToString(i)).Attributes.Add("class","blah"));

How is it possible to add a new ListItem with a 'class' attribute in a single line of code?


Solution

  • You cannot do that, because Attributes.Add() does not return a ListItem object.

    See documentation: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.attributecollection.add?view=netframework-4.7.2#System_Web_UI_AttributeCollection_Add_System_String_System_String_

    You can either use the old way

    ListItem newListItem = new ListItem("my value", "my value");
    newListItem.Attributes.Add("class", "blah");
    myDropDownList.Items.Add(newListItem);
    

    or rewrite your version of Add().