【问题标题】:asp.net Repeater - get Reference to current Itemasp.net 中继器 - 获取对当前项目的引用
【发布时间】:2015-02-08 15:46:51
【问题描述】:

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

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

在这个中继器中,我想引用当前的迭代项。 我知道我可以使用&lt;%#Item%&gt; 并且我可以使用&lt;%#Container.DataItem%&gt;。如果我想进入某个领域,我可以使用&lt;%#Item.fieldName%&gt; 或 Eval 它。

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

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

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

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

【问题讨论】:

  • 我会改用ItemDataBound。这使得代码更具可读性、可维护性和健壮性(编译时类型安全)。
  • 怎么做?我不熟悉这个

标签: c# asp.net data-binding repeater dataitem


【解决方案1】:

我会改用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">

【讨论】:

  • 但这是服务器端的。我需要像这样在页面端使用它 你可以获得 50% 的折扣!
  • @Programer: 这也在服务器端执行。您可以以更具可读性的方式获得相同的代码。但是您必须展示更多您正在尝试做的事情以及所涉及的控件,否则我无法向您展示完整的示例。
  • 我知道,但我希望它出现在动态页面上而不是函数中。如果条件以您的方式有效,我如何打印到 html?
  • @Programer:那么你必须等待另一个答案。我不知道也不想知道如何使用内联 aspx 做类似的事情。这更像是经典的 ASP 而不是 ASP.NET。
猜你喜欢
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
相关资源
最近更新 更多