views:

224

answers:

2

Hi

I like to handle and compare a lot of date times in my repeater even I have to work more than one time with the same.

It's a bit ugly, to cast everywhere the Eval("MyDate") like ((DateTime)Eval("MyDate")) to substract 2 datetimes or to compare it, even if you have to do this more than in one operation.

I thought of saving all the evals in a var at start of the repeater?

DateTime mydt1 = Eval("myDate");
DateTime mydt2 = Eval("mydate");

after that, it's easy to do any operations in the whole repeater. Hope you understand my idea. Is this possible? I tried short but everytime errors.

mydt1 - mydt2....

Thank you and best regards.

+1  A: 

If you want to add more logic to your repeater I would suggest you move the binding logic to the code behind:

ASPX:

<asp:Repeater id="myRepeater" runat="server">
    <ItemTemplate>
        <asp:Literal id="myLiteral" runat="server" />
    </ItemTemplate>
</asp:Repater>

CS:

protected override void OnInit(EventArgs e)
{
    myRepeater.ItemDataBound += myRepeater_ItemDataBound;
    base.OnInit(e);
}

void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // this method will be invoked once for every item that is data bound

    // this check makes sure you're not in a header or a footer
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {

        // this is the single item being data bound, for instance, a user, if 
        // the data source is a List<User>
        User user = (User) e.Item.DataItem;

        // e.Item is your item, here you can find the controls in your template

        Literal myLiteral = (Literal) e.Item.FindControl("myLiteral");

        myLiteral.Text = user.Username + ", " + user.LastLoginDate.ToShortDateString();

        // you can add any amount of logic here
        // if you need to use it, e.Item.ItemIndex will tell you what index you're at
    }
}
David Hedlund
+3  A: 

You could call a method on the code behind page from the repeater using the DateTimes as arguments. The casting logic can be done in the code behind if the goal it to create a cleaner looking aspx page.

Example ASPX:

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Literal 
            ID="Literal1" 
            runat="server" 
            Text='<%# DateFoo(Eval("myDate1"), Eval("myDate2")) %>' />
    </ItemTemplate>
</asp:Repeater>

Example C# code behind:

protected string DateFoo(Object o1, Object o2)
{
    DateTime? dt1 = o1 as DateTime?;
    DateTime? dt2 = o2 as DateTime?;

    // Do logic with DateTimes

    return "string";
}
sirchristian