c# - 格式化某些绑定(bind)到 Repeater 的项目的输出

标签 c# asp.net data-binding repeater itemdatabound

例如,在后端,我将一个数据表绑定(bind)到一个转发器,而在前端,我正在这样设置我的转发器:

<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
   <ItemTemplate>
     <div class="user">
         Name:   <%# DataBinder.Eval(Container, "DataItem.Name")%>
         Email:  <%# DataBinder.Eval(Container, "DataItem.Email")%>
         Active: <%# DataBinder.Eval(Container, "DataItem.Active")%>
         Status: <%# DataBinder.Eval(Container, "DataItem.Status")%>
     </div>
    </ItemTemplate>
</asp:Repeater>

所以“name”和“email”的输出没问题。然而,“事件”和“状态”打印出一个整数代码,我想根据我的引用表将其更改为更具描述性的字符串。

我猜我可以在中继器的“ItemDataBound”事件上执行此操作,但我坚持下一步应该做什么,即检查我需要修改和更改的两个字段。

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        //Do modifications here
    }
}

最佳答案

你可以

  1. 处理 ItemDataBound 事件中的格式
  2. 在您的 Page 或 WebUserControl 类中创建公共(public)方法来处理格式设置。

使用选项 1 将要求您声明一个控件(例如标签)来存储每个字段的值,如下所示:

<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
   <ItemTemplate>
     <div class="user">
             <asp:Label ID="ActiveLabel" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name")%>'></asp:Label>
     </div>
    </ItemTemplate>
</asp:Repeater>

然后在您的 ItemDataBound 事件中,您可以找到该控件并根据需要设置它的值。

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
            Label activeLabel = (Label)e.Item.FindControl("ActiveLabel");

            //Format label text as required
    }
}

使用选项 2 将要求您创建一个服务器端可公开访问的方法,您可以像这样调用它:

<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
   <ItemTemplate>
     <div class="user">
     Active: <%# FormatActive((string)DataBinder.Eval(Container, "DataItem.Active")) %>
     </div>
    </ItemTemplate>
</asp:Repeater>

然后像这样定义一个方法:

public string FormatActive(string input)
{
     //Format as required
     //Return formatted string
}

关于c# - 格式化某些绑定(bind)到 Repeater 的项目的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7995200/

相关文章:

c# - MVVM 和依赖注入(inject)

c# - 如何通过代理连接到Azure服务总线主题-C#?

Javascript 在文本框中输入值时 trim 空格

c# - Visual Studio 在构建期间编译 WPF 应用程序两次

C# ListView : ListViewItem offset possible?

c# - "new"c# 属性声明中的关键字

asp.net - 我需要 javascript css 生成器吗?

javascript - 在 v-for 之后将模态绑定(bind)到相应的按钮

JavaFx 8 双向绑定(bind)

c# - 来自列表的 WPF Listview 数据绑定(bind)