ASP.NETC#-维护DataGrid列宽度
创始人
2024-09-17 06:30:19
0

为了使DataGrid在 postback(提交表单)后保留列宽度,我们需要在 DataGrid 的 ItemDataBound 事件中存储列宽度,并在每个 postback 之后将其重新应用。

首先,在 DataGrid 的 ItemDataBound 事件中,我们可以使用 JavaScript 将列宽度存储在 cookie 中,以便在 postback 之后可以检索。

protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        for (int i = 0; i < e.Item.Cells.Count; i++)
        {
            e.Item.Cells[i].Attributes.Add("onclick",
                "storeColumnWidths('" + e.Item.ClientID + "','" +
                e.Item.Cells[i].ClientID + "')"
            );
        }
    }
}

然后,在 master page 或网页的 Page_Load 事件中,我们可以检查是否存在 cookie 以存储之前的列宽度,并在 DataGrid 初始化时应用这些值。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        HttpCookie cookie = Request.Cookies["ColumnWidths"];
        if (cookie != null)
        {
            string[] widths = cookie["Widths"].Split(new char[] { ',' });
            for (int i = 0; i < widths.Length; i++)
            {
                if (i < grid.Columns.Count)
                {
                    grid.Columns[i].ItemStyle.Width = Unit.Parse(widths[i]);
                    grid.Columns[i].HeaderStyle.Width = Unit.Parse(widths[i]);
                }
            }
        }
    }
}

protected void grid_Init(object sender, EventArgs e)
{
    HttpCookie cookie = Request.Cookies["ColumnWidths"];
    if (cookie != null)
    {
        string[] widths = cookie["Widths"].Split(new char[] { ',' });
        for (int i = 0; i < widths.Length; i++)
        {
            if (i < grid.Columns.Count)
            {
                grid.Columns[i].ItemStyle.Width = Unit.Parse(widths[i]);
                grid.Columns[i].HeaderStyle.Width = Unit.Parse(widths[i]);
            }
        }
    }
}

最后,在每个 postback 之后,我们需要将列宽度存储在 cookie 中,以便在下一个 postback 时可以应用它们。

protected void Page_PreRender(object sender, EventArgs e)
{
    HttpCookie cookie = new HttpCookie("ColumnWidths");
    string widths = "";
    foreach (DataGridColumn column in

相关内容

热门资讯

第5新版(来玩app)外挂透明... 此外,数据分析德州(来玩app)辅助神器app还具备辅助透视行为开挂功能,通过对客户来玩app透明挂...
8个打法!wepoke透明挂辅... 8个打法!wepoke透明挂辅助软件是真的(插件)透视(存在有挂)-哔哩哔哩;玩家必备必赢加哟《13...
四小程序!雀神微信小程序怎么开... 您好,雀神微信小程序怎么开挂这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多...
1个大厅!德扑ai操作(手牌胜... 1个大厅!德扑ai操作(手牌胜率计算工具)辅助透视(有挂实锤)-哔哩哔哩1、每一步都需要思考,不同水...
九黑科技(wepoke app... 九黑科技(wepoke app)外挂透明挂辅助APP(透视)技巧教程(真是有挂)-哔哩哔哩;wepo...
5个app技巧!微扑克机制技巧... 1、5个app技巧!微扑克机制技巧(插件)辅助透视(新版有挂)-哔哩哔哩(UU poker、微扑克机...
第五真的有挂!雀神微信小程序免... 第五真的有挂!雀神微信小程序免费辅助器(辅助挂)太坑了原来真的有挂(有挂透明挂)-哔哩哔哩1、用户打...
第一个脚本!德扑之星软件模拟器... 第一个脚本!德扑之星软件模拟器(作弊)透视辅助(揭秘有挂)-哔哩哔哩;支持多人共享记分板与复盘,通过...
四个规律!wepoke科技(软... 四个规律!wepoke科技(软件透明挂)辅助挂(有挂猫腻)-哔哩哔哩;wepoke科技黑科技是一款具...
第三开挂(aapoker开发)... 第三开挂(aapoker开发)外挂透明挂辅助机制(透视)高科技教程(有挂讲解)-哔哩哔哩是一款可以让...