c# - 如何在 ASP Repeater 中为名称列表创建大写字母行

标签 c# asp.net

enter image description here

我正在使用 asp 转发器来显示名称列表,并且我想将当前字母显示为一种分组标题,就像在索引页中一样。

数据在绑定(bind)之前按字母顺序排序,但我发现很难在显示名称之前插入“A”和“B”。

最佳答案

将可见性设置为 False 的面板控件添加到您的 ItemTemplate。当您绑定(bind)中继器时(假设您正在订阅 ItemDataBound 事件),运行检查以查看第一个字母是否已更改。如果有,将面板的可见性设置为 true 并打印出该字母。

如果您需要一些示例代码,请告诉我。

编辑:示例代码

为了清楚起见,“AlphaHeaders”就是我们要显示的“A”、“B”、“C”字母的名称

aspx代码

Repeater 看起来像这样:

<table>
    <asp:Repeater id="rptRepeater" runat="server" OnItemDataBound="rptNames_OnItemDataBound">
        <ItemTemplate>
            <asp:Panel id="pnlAlphaHeader" runat="server" visible="False">
               <tr><td><asp:Label id="lblAlphaHeader" runat="server" /></td></tr>
            </asp:Panel>
            <tr><td><asp:Label id="lblName" runat="server" /></td></tr>
        </ItemTemplate>
    </asp:Repeater>
</table>

aspx.cs代码

首先,您需要一个保存当前 AlphaHeader 的变量:

private string _AlphaHeaderCurrent = String.Empty;

然后您将在中继器的 OnItemDataBound 事件上完成您的工作:

protected void rptNames_OnItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
   if ((e.ItemType==ListItemType.Item) || (e.ItemType==ListItemType.AlternatingItem)) {
      string name = e.Item.DataItem("Name").ToString();
      //check if the first letter of the current name is new. If it is new, we print out the header
      if(!name.StartsWith(this._AlphaHeaderCurrent)) {
         this._AlphaHeaderCurrent = name.SubString(1);                               
         ((Panel)e.ItemFindControl("pnlAlphaHeader")).Visible = true;
         ((Label)e.Item.FindControl("lblAlphaHeader")).Text = the._AlphaHeader;
      }
      ((Label)e.Item.FindControl("lblName")).Text = name;          
   }
}

关于c# - 如何在 ASP Repeater 中为名称列表创建大写字母行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14834335/

相关文章:

c# - 在不添加引用的情况下调用另一个项目的类

c# - Microsoft AntiXSS - 是否需要解码?

c# - 在VS2010中的Web应用程序中运行Main方法

c# - 双重确认从数据库中删除ITEM?

c# - 计算机崩溃后 VS 2013 未加载 'Antlr3.Runtime' 程序集

asp.net - IIS 7.5、8.0、8.5 HTTP 错误 403.14 - 安装干净的 Windows 后禁止

c# - 拐角处的圆线段碰撞

c# - 使用 Entity Framework 4 和 Linq 查询比较 DateTime 属性中的日期的简单方法

c# - 独立于 DataTable 存储 DataRow - RowNotInTableException

c# - 如何将网站翻译成另一种语言?(ASP .NET, c#)