ASP.NET中回发后如何修改分页LinkButton的颜色
问题分析
回发后所有页码按钮会被重新绑定渲染,默认样式会覆盖选中状态,因此需要在绑定分页Repeater时,主动给当前页码的按钮标记特殊样式。
解决方案步骤
1. 添加选中状态的CSS类
在现有CSS中新增类,用于标记当前选中的页码:
a:hover, a:focus{ color:white; background-color:black; } /* 当前选中页码样式 */ .active-page { background-color: black !important; color: white !important; }
2. 修改前端Repeater代码,添加ItemDataBound事件
给分页Repeater加上OnItemDataBound="rptPaging_ItemDataBound"属性:
<asp:Repeater ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand" OnItemDataBound="rptPaging_ItemDataBound"> <ItemTemplate> <asp:LinkButton ID="lnkPage" Style="padding: 8px; margin: 2px; background: lightgray; border: solid 1px #666;font-weight: bold;" CommandName="Page" CommandArgument="<%# Container.DataItem %>" runat="server" CssClass="listbtn" ForeColor="Black" Font-Bold="True"><%# Container.DataItem %> </asp:LinkButton> </ItemTemplate> </asp:Repeater>
3. 后台添加ItemDataBound事件处理逻辑
在后台代码中新增rptPaging_ItemDataBound方法,判断当前项是否为当前页码并添加选中样式:
protected void rptPaging_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { // 获取当前项的页码值 string currentPageText = e.Item.DataItem.ToString(); int currentPage = Convert.ToInt32(currentPageText); // 当前选中页码为PageNumber + 1(PageNumber从0开始,页码从1开始) if (currentPage == PageNumber + 1) { LinkButton lnkPage = (LinkButton)e.Item.FindControl("lnkPage"); // 添加选中状态的CSS类 lnkPage.CssClass += " active-page"; } } }
4. 逻辑验证
- 点击页码后,
PageNumber会被设置为选中页码-1(对应PagedDataSource的CurrentPageIndex) - 重新绑定分页Repeater时,
ItemDataBound事件会遍历每个页码按钮,给与当前PageNumber匹配的按钮添加选中样式 - 回发后样式会保留,用户能清晰识别当前所在页码
内容的提问来源于stack exchange,提问作者Amelia
相关产品推荐
相关产品推荐

