views:

650

answers:

2

I have an Asp.Net GridView. One of the Columns is a List, but I only want to show the Last Item in the list. How can I do this?

List<string> Column1

I am binding the Gridview to a business object:

public Class GridObject
{
    List<string> Column1 { get; set; }
}

EDIT

This worked, but is it the best solution:

<%# ((List<string>)Eval("Column1"))[((List<string>)Eval("Column1")).Count - 1] %>
A: 

Your best bet is to create a template column and use an inline script to retrieve the value from the list:

<%= ((List<string>)DataBinder.Eval("Column1"))[((List<string>)DataBinder.Eval("Column1")).Count] %>

Or you could store the result in the text of a label or a literal.

Hope that helps

LorenVS
Didn't work, see edit to question.
Martin
Sorry about that, right idea, forgot to subtract 1... Looks like you figured that our though :)
LorenVS
and the DataBinder.Eval takes 2 or 3 parameters, and the = should be #
Martin
+3  A: 

I would add a property to the object you are binding to, and use that property instead of the list property in your binding.

public Class GridObject
{
    List<string> Column1 { get; set; }
    public string Column1LastValue
    { 
      get
      {   // return Column1.Last(); if linq is available
          return Column1[Column1.Count-1];
      }
    }
}

Edit: Adding a presentation wrapper allows you to unit test what will be displayed. You are doing a translation in the view, which is OK, but since you technically have some logic happening to translate your business object to something proper for display, you would likely want to unit test that translation. Then, any formatting you want to apply to any of your business object fields is wrapped in a testable class, rather than hidden on the untestable view. Here is a sample of how this could be done:

public class GridObjectView
{
    private GridObject _gridObject;

    public GridObjectView(GridObject gridObject)
    {
        _gridObject = gridObject;
    }

    public string Column1
    {
        get
        {
            return _gridObject.Column1.Last();
        }
    }
}

Then to do the databinding, you could do this:

List<GridObject> data = GetGridData();

grid.DataSource = data.Select(g => new GridObjectView(g));
grid.DataBind();
NerdFury
Not really that feasible ... object is a business object, and I don't want to add a presentation property to a business object
Martin
Then you can create a GridObjectView class that wraps it for the purpose of preparing the object for display on the view.
NerdFury
Is that a better solution that the one I currently have? If yes, why? (not being a d*ck, just trying to learn)
Martin
see my edits above. The advantage is testability.
NerdFury