我正在使用 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/