4

我正在使用 Asp.net 4.5,C#。我有一个带有一些 DataSource Bind 的 reapter:

  <asp:Repeater ItemType="Product" ID="ProductsArea" runat="server">
            <HeaderTemplate></HeaderTemplate>
            <ItemTemplate>
                ...  
            </ItemTemplate>
            <FooterTemplate></FooterTemplate>
        </asp:Repeater>    

在这个中继器中,我想引用当前的迭代项。我知道我可以使用<%#Item%>并且我可以使用<%#Container.DataItem%>。如果我想进入一个领域,我可以使用<%#Item.fieldName%>或评估它。

但是我想在一个字段上设置一个条件,我怎样才能获得对#Item的引用才能执行以下操作:

<% if (#Item.field>3)%>, <%if (#Container.DataItem.field<4)%> 

我希望 acautley 有这样的参考 <%var item = #Item%> 而不是在我需要的时候使用它。

当然上面的语法是无效的,如何实现这个properley?

4

1 回答 1

0

我会ItemDataBound改用。这使得代码更具可读性、可维护性和健壮性(编译时类型安全)。

protected void Product_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        // presuming the source of the repeater is a DataTable:
        DataRowView rv = (DataRowView) e.Item.DataItem;
        string field4 = rv.Row.Field<string>(3); // presuming the type of it is string
        // ...
    }
}

转换e.Item.DataItem为实际类型。如果您需要在ItemTemplate使用中找到一个控件e.Item.FindControl并适当地进行转换。当然,您必须添加事件处理程序:

<asp:Repeater OnItemDataBound="Product_ItemDataBound" ItemType="Product" ID="ProductsArea" runat="server">
于 2014-12-10T12:42:05.710 回答