You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Repeater_ItemCommand中结合ViewState使用代码?(Asp.Net)

嘿,我来帮你搞定回发后样式丢失的问题!核心思路是把选中的页码状态存在ViewState里,然后在GridView每次绑定数据的时候(包括回发后的重新绑定),从ViewState取出这个状态,重新给对应单元格设置样式。这样就不会因为回发导致样式丢失了。

步骤1:修改Repeater_ItemCommand事件,保存选中页码到ViewState

原来的代码里直接设置样式,但回发后这些样式会被重置,所以我们先把选中的页码存起来,再触发GridView重新绑定:

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "PageNumbers")
    {
        // 把选中的页码存入ViewState,这是关键的状态保存
        int selectedPage = Convert.ToInt32(e.CommandArgument);
        ViewState["SelectedPageIndex"] = selectedPage;

        // 设置GridView页码并重新绑定,触发DataBound事件
        GridView1.PageIndex = selectedPage;
        GridView1.DataBind();
    }
}

步骤2:在GridView的DataBound事件中重新应用样式

每次GridView绑定数据(包括回发后的绑定)时,我们从ViewState取出保存的页码,找到对应的单元格设置样式,同时重置其他单元格的样式:

protected void GridView1_DataBound(object sender, EventArgs e)
{
    // 先检查ViewState里有没有保存的选中页码
    if (ViewState["SelectedPageIndex"] == null) return;

    int selectedPageIndex = Convert.ToInt32(ViewState["SelectedPageIndex"]);
    
    // 找到顶部分页行里的Repeater
    Repeater repeatTD = GridView1.TopPagerRow?.FindControl("Repeater1") as Repeater;
    if (repeatTD == null) return;

    foreach (RepeaterItem item in repeatTD.Items)
    {
        // 这里假设你用LinkButton来显示页码,替换成你实际的页码控件ID
        LinkButton pageBtn = item.FindControl("PageNumberBtn") as LinkButton;
        HtmlTableCell cell = item.FindControl("cell") as HtmlTableCell;

        if (pageBtn != null && cell != null)
        {
            if (Convert.ToInt32(pageBtn.CommandArgument) == selectedPageIndex)
            {
                // 给选中的页码单元格设置样式
                cell.Attributes["style"] = "background-color:blue";
            }
            else
            {
                // 重置其他单元格的样式,避免残留
                cell.Attributes["style"] = ""; // 或者设置你的默认样式,比如background-color:white
            }
        }
    }
}

别忘了注册DataBound事件

最后要确保你的GridView控件已经绑定了DataBound事件,在ASPX页面的GridView标签里加上:

<asp:GridView ID="GridView1" runat="server" OnDataBound="GridView1_DataBound" ...>
    <!-- 其他配置 -->
</asp:GridView>

为什么要这么做?因为回发时页面上的控件会重新渲染,之前直接设置的样式不会被保留。但ViewState会在回发时保留我们存储的选中页码,所以在每次GridView绑定数据时,我们用这个状态重新给对应单元格设置样式,就能保证样式在回发后依然存在啦。

内容的提问来源于stack exchange,提问作者Raniel Quirante

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 07:04:50