ASP.NET:如何在 DataBind 期间设置控件的 css 类?

标签 asp.net css

使用 asp:Repeater 生成表格行:

<asp:repeater ID="announcementsRepeater" OnItemDataBound="announcementsRepeater_ItemDataBound" runat="Server">
   <itemtemplate>
      <tr id="announcementRow" class="announcementItem" runat="server">...</tr>
   </itemtemplate>
</asp:repeater>

现在在数据绑定(bind)中,我想用不同的 css 类标记“未读”公告,以便网络专家可以执行他想要区分已读和未读公告的任何样式:

protected void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
      return;

   // get the associated data item
   Announcement announcement = (Announcement)e.Item.DataItem;

   WebControl row = (WebControl)e.Item.FindControl("announcementRow");
      if (row != null)
         row.CssClass = row.CssClass + " announcementItemUnread";
}

除了运行时转换失败:

System.InvalidCastException occurred
  Message="Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableRow' to type 'System.Web.UI.WebControls.WebControl'."

事实证明HtmlTableRow具有与 WebControl 不同的父层次结构:

HtmlTableRow
   : HtmlContainerControl
      : HtmlControl
         : System.Web.UI.Control

WebControl 的最终来源

WebControl
   : System.Web.UI.Control

所以我更改了代码以尝试改用 System.Web.UI.Control:

Control row = (Control)e.Item.FindControl("announcementRow");
if (row != null)
   row.CssClass = row.CssClass + " announcementItemUnread";

但是Control不包含 CssClass 的定义:

'System.Web.UI.Control' does not contain a definition for 'CssClass'    

那么我如何为 <TR> 设置 css 类名呢? DataBind 期间的元素?

最佳答案

   HtmlControl htmlRow = (HtmlControl)row; 
   htmlRow.Attributes["class"] = htmlRow.Attributes["class"] + " announcementItemUnread";

关于ASP.NET:如何在 DataBind 期间设置控件的 css 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/183415/

相关文章:

html - 在 :before of div need to apply height of image?

css - Suckerfish 下拉菜单在 IE 8 中不起作用

c# - 从调试中检索远程调用失败的 AD 组成员资格

c# - 在构建后事件中更新本地 nuget 包

css - 你能在 div 中放置一个样式 block 吗

asp.net - Visual Studio 2015 nuget 解决方案未保存如何修复?

c# - 如何在 ASP.NET 中动态创建的 TreeView 中添加 URL?

Css float 缺点

ellipsis - 文本溢出问题 : ellipsis

javascript - 仅切换上一类