Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: How to set the css class of a Control during DataBind?

Tags:

css

asp.net

A table row is generated using an asp:Repeater:

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

Now in the data-bind i want to mark "unread" announcements with a different css class, so that the web-guy can perform whatever styling he wants to differentiate between read and unread announcements:

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";
}

except the cast fails at runtime:

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

It turns out that HtmlTableRow has a different parent heirarchy than WebControl:

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

which is ultimately where WebControl comes from

WebControl
   : System.Web.UI.Control

So i changed the code to try to use a System.Web.UI.Control instead:

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

But Control doesn't contain a definition for CssClass:

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

so how do i set the css class name for a <TR> element during DataBind?

like image 282
Ian Boyd Avatar asked Oct 08 '08 15:10

Ian Boyd


1 Answers

   HtmlControl htmlRow = (HtmlControl)row; 
   htmlRow.Attributes["class"] = htmlRow.Attributes["class"] + " announcementItemUnread";
like image 92
tvanfosson Avatar answered Oct 19 '22 22:10

tvanfosson