在数据绑定上使用新的 ListItem 时如何添加 css class?

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

我正在使用循环将一些值添加到下拉列表中:

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

我想同时为新的 ListItem 添加一个 CSS 属性。我看到我可以使用

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

然而,我能找到的唯一方法是将我的单行代码分解为 3 行单独的代码,如下所示:

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

智能感知允许我编写以下代码,但它出错并显示“'System.Web.UI.WebControls.ListItemCollection.Add(string)' 的最佳重载方法匹配有一些无效参数。

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

如何在一行代码中添加具有 'class' 属性的新 ListItem?

你不能这样做,因为 Attributes.Add() 不是 return ListItem 对象。

查看文档:https://docs.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_

您可以使用旧方法

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

重写您的 Add() 版本。

我建议将 css 添加到 myDropdownList,然后让 CSS 选择列表中的项目。这就是 CSS 设计的工作方式。

// this Markup    
<asp:DropDownList ID="myDropdownList " runat="server">
</asp:DropDownList>

// can have a CSS class added on the server like this
this.myDropdownList.Css = "blah";
myDropdownList.Datasource = data;
myDropdownList.DataBind();


// which will render on the page like this
<select class="blah" id="myDropdownList">
     <option>Foobar 1</option> 
     <option>Foobar 2</option> 
     <option>Foobar 3</option> 
</select>


// which you can apply CSS styling to like this
select.blah option {
  flont-size:large;
  color: #aaa;
  font-type:italics;
}