views:

432

answers:

4

Hi there,

is there any easy way to style the last item in a ListView control? Basicly need to append a class.

Cheers

+2  A: 

There is

:last-child

pesudo class.

But won't work in all browsers.

The best way is to add a css class to the last item in the listview and style it.

If you can use jQuery then you can use the

:last-child

selector

rahul
A: 

phoenix's answer doesn't really answer the question, phoenix suggests styling the last item with a different css class, but how do you know which item is the last item? ListView has no LastItemTemplate.

You can use <%# Container.DisplayIndex %> to get your position in the current list. You can use Items.Count on the Control to get the total but combining these two things is slightly beyond my ASP.NET skills.

Tim Clark
+2  A: 

Comma separate a list of customers names. The last customer name will end with a dot.

Customer A, Customer B, Customer C.

<asp:ListView ID="lvCustomers" runat="server">
  <LayoutTemplate>
    <div id="itemPlaceHolder" runat="server"></div>
  </LayoutTemplate>
  <ItemTemplate>
    <%# Eval("CustomerName")<%# Container.DisplayIndex == (Container.BindingContainer.As<ListView>().DataSource.As<System.Collections.Generic.List<String>>().Count - 1) ? "." : ", " %>
  </ItemTemplate>
</asp:ListView>

This uses an extension method 'As':

/// <summary>
/// Returns this object casted as a different type.
/// </summary>
/// <typeparam name="T">A type</typeparam>
/// <param name="obj">An object</param>
/// <returns>A boolean value.</returns>
public static T As<T>(this object obj) where T : class
{
    if (obj == null) return null;

    return obj as T;
}
mathijsuitmegen
+1  A: 

I do this kind of stuff in the ItemDataBound listview event. But for that purpose I need to know what would be the type of the DataSource.

For example:

protected void LvFilters_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem item = e.Item as ListViewDataItem;
        if(item.DataItemIndex == ((YourDataSourceType)lvFilters.DataSource).Count - 1)
            e.Item.FindControl("Control's id here").Visible = false; // or whatever you wanna do about styling
    }
}
Shedal