views:

41

answers:

1

I am having trouble displaying my object in a datalist.

My object loks like this:

public class Course
{
    private string courseName;
    private DateTime[] courseDates;

    public string CourseName
    {
        get { return courseName; }
        set { courseName = value; }
    }
    public DateTime[] CourseDates
    {
        get { return courseDates; }
        set {
            foreach (DateTime dt in courseDates)
            {
                if (dt < DateTime.Now)
                    throw new Exception("The date of the course has to be after todays date.");
            }
            courseDates = value; }
    }

    public Course(string _courseName, DateTime[] _courseDates)
    {
        courseName = _courseName;
        courseDates = _courseDates;
    }
}

When I try to display it in a datalist the name of the course looks ok. But The dates are not shown.

So I was thinking I needed a nested datalist but then I don't know how to fill the second datalist with the dates in the object.

+1  A: 

I've show two solutions:

<asp:DataList ID="DataList1" runat="server" 
        onitemdatabound="DataList1_ItemDataBound"> 
    <ItemTemplate>
        <td><%# DataBinder.Eval(Container.DataItem, "CourseName")%></td>
        <td><%# RenderDates( DataBinder.Eval(Container.DataItem, "CourseDates"))%></td>
        <td>
            <asp:DataList ID="DateList" runat="server">
                <ItemTemplate>
                    <td><%# Container.DataItem%></td>
                </ItemTemplate>
            </asp:DataList>            
        </td>
    </ItemTemplate>       
</asp:DataList>

and

public string RenderDates(object dates)
{
    DateTime[] ds = dates as DateTime[];
    StringBuilder sb = new StringBuilder();
    if( ds != null && ds.Length > 0)
    {
        sb.Append(ds[0]);
        for (int i = 1; i < ds.Length; i++)
        {
            sb.AppendFormat(" - {0}", ds[i]);
        }
    }
    return sb.ToString();
}

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
    DataListItem item = e.Item;
    if ((item.ItemType == ListItemType.Item) ||
        (item.ItemType == ListItemType.AlternatingItem))
    {
        var innerList= (DataList)item.FindControl("DateList");
        innerList.DataSource = ((Course) item.DataItem).CourseDates;
        innerList.DataBind();
    }
}
Mikael Svenson
I thought there would be a simpler way. However this works great.Thank you!
Fred