tags:

views:

3156

answers:

4

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?

+1  A: 

Cast it to HtmlTableRow

HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("announcementRow");
Geoff
HtmlTableRow does not contain a CssName property either:'System.Web.UI.HtmlControls.HtmlTableRow' does not contain a definition for 'CssClass'
Ian Boyd
+3  A: 
   HtmlControl htmlRow = (HtmlControl)row; 
   htmlRow.Attributes["class"] = htmlRow.Attributes["class"] + " announcementItemUnread";
tvanfosson
A: 

Why not just bind in the declaration?

<tr id="announcementRow" runat="server" class="<#% functionToDetermineWhichtoShow(ItemInBoundSetToPass) %>">...</tr>
tr element doesn't have a cssClass, only ASP.NET controls do. In this case you'd need a function to set the class attribute. Probably easier just to do it in the code-behind.
tvanfosson
Also, i'd rather not hide the css class names that i'll be assigning too much from the web-designer.
Ian Boyd
A: 

HtmlTableRow htmlRow = (HtmlTableRow)row;
htmlRow.Attributes.Add("class","announcementItemUnread");