需要在Repeater DataBind事件之后运行一些代码

时间:2014-01-09 15:38:51

标签: c# asp.net data-binding

我正在为停车场写一个程序;它已接近完成,但我正在工作或报告,需要使数据简单可靠;为此,我有一个中继器;在DataBind事件之后;我想使用'循环'将前色素应用于内部转发器标签,该标签在数据绑定后保存某些文本结果;以及使用DateTime.Now - 数据绑定标签中的日期显示计算的时间跨度。我的代码仅适用于转发器中的第一个结果。

FIndAny是一个访问内部控件的小类;请忽略;只是帮我提供一些关于如何做这样的事情的示例代码。

以下是代码示例:

Repeater1.DataBind();
//int i=0;
//Label dc = c;
foreach (RepeaterItem t in Repeater1.Items)
{
    ((Label)(FIndAny(Repeater1, "Label41"))).Text = 
        Convert.ToString((DateTime.Now - DateTime.Parse(((Label)(FIndAny(Repeater1, "Label9"))).Text)).TotalHours);
}     

Label6.Text = "View Time trace below...";
Label lbl = ((Label)FIndAny(Repeater1, "Label11"));

if (((Label)FIndAny(Repeater1, "Label13")).Text == "Parked" && (mdx.cardstatus.Where(x => x.CardNum == lbl.Text)).All(x => x.Status == 1))
{
    ((Panel)FIndAny(Repeater1, "Panel1")).BorderColor = System.Drawing.Color.Red;
    ((Panel)FIndAny(Repeater1, "Panel1")).BorderStyle = BorderStyle.Solid;
    ((Panel)FIndAny(Repeater1, "Panel1")).BorderWidth = 5;
    ((Label)FIndAny(Repeater1, "Label13")).BackColor = System.Drawing.Color.Red;
    ((Label)FIndAny(Repeater1, "Label13")).Font.Bold = true;
    ((Label)FIndAny(Repeater1, "Label13")).ForeColor = System.Drawing.Color.White;
}

2 个答案:

答案 0 :(得分:1)

您正在寻找Repeater.ItemDataBound Event,这是在Repeater控件中的项目受数据限制但在页面上呈现之前发生的。

    Repeater1.ItemDataBound += new RepeaterItemEventHandler(Repeater1ItemDataBound);
    Repeater1.DataBind();
}

void Repeater1ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
        Label label13 = (Label)e.Item.FindControl("Label13");
        if (label13.Text == "Parked") {
        //..... etc
    }
}

答案 1 :(得分:1)

在aspx页面上试试

<asp:Repeater OnItemDataBound="Repeater_ItemDataBound" ID="Repeater" runat="server">
    <ItemTemplate>
        <asp:Label ID="MyLabel" runat="server" Text="Label"></asp:Label>
    </ItemTemplate>
</asp:Repeater>

然后是代码隐藏

protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item)
    {
        Label myLabel = e.Item.FindControl("MyLabel") as Label;
        YourItemObject itemObject = e.Item.DataItem as YourItemObject;
        myLabel.Text = itemObject.SomeAttribute;
    }
}

希望有所帮助:)