龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

asp.net实例操作显示及隐藏GridView列头的方法

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
GridView这个控件太方便了,很多人都使用吧,下面介绍如何显示与隐藏GridView的列头。 这是一个任务管理系统的示例,它可能就没有必要总是显示任务ID列,还有打印任务列表的时候,可

GridView这个控件太方便了,很多人都使用吧,下面介绍如何显示与隐藏GridView的列头。

这是一个任务管理系统的示例,它可能就没有必要总是显示任务“ID”列,还有打印任务列表的时候,可能不需要"Assigned To" 列.

     下面是一个演示的Gridview,它只显示了4列.

 

通过点击列头的负号,用户能隐藏一列;下图中,“Id”列被隐藏了.

隐藏列可再次可见通过选择 "Show Column"下拉菜单让其显示.当一列刚被隐藏后,它将出现在 "Show Column"中的第一个位置。

下面是在一页打印预览,ID为隐藏的列:

这篇文章将会演示两种显示和隐藏GridView列的方法,一种是客户端的方法,另外一种是服务段的方法.

 在客户段显示和隐藏GridView的列

大部分代码是在GridView的RowCreated事件生成客户端的功能的。当GridView的Header行被创建后,一个带负号的HyperLink被插入每个Header行的单元格中用来隐藏列。 这个hyperlink通过它的onclick事件调用一个HideCol的Javascript方法,CSS类用来增加负号的大小,当每个数据行被创建的时候,一个Id将会被添加到每行中用来让Javascript区分每一行.

C# Code [http://www.xueit.com]
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    GridView gridView = (GridView)sender;
    StringBuilder sb = new StringBuilder();

    // For the header row add a link to each header
    // cell which can call the HideCol javascript method
    if (e.Row.RowType == DataControlRowType.Header)
    {
        // Loop through each cell of the row
        for (int columnIndex = 0; columnIndex < e.Row.Cells.Count; columnIndex  )
        {
            // Build the hide column link
            sb.Remove(0, sb.Length); // first empty the StringBuilder
            sb.Append("javascript:HideCol('");
            sb.Append(gridView.ClientID);
            sb.Append("', ");
            sb.Append(columnIndex);
            sb.Append(", '");
            sb.Append(columnNames[columnIndex]);
            sb.Append("');");

            // Build the "Hide Column" HyperLink control
            HyperLink hideLink = new HyperLink();
            hideLink.Text = "-";
            hideLink.CssClass = "gvHideColLink";
            hideLink.NavigateUrl = sb.ToString();
            hideLink.Attributes.Add("title", "Hide Column");

            // Add the "Hide Column" HyperLink to the header cell
            e.Row.Cells[columnIndex].Controls.AddAt(0, hideLink);

            // If there is column header text then
            // add it back to the header cell as a label
            if (e.Row.Cells[columnIndex].Text.Length > 0)
            {
                Label columnTextLabel = new Label();
                columnTextLabel.Text = e.Row.Cells[columnIndex].Text;
                e.Row.Cells[columnIndex].Controls.Add(columnTextLabel);
            }
        }
    }

    // Give each row an id
    if (e.Row.RowType == DataControlRowType.Pager)
        e.Row.Attributes.Add("id", gridView.ClientID   "_pager");
    else
        e.Row.Attributes.Add("id", gridView.ClientID   "_r"   e.Row.RowIndex.ToString());
}

SetupShowHideColumns方法中生成“Show Columns”下拉菜单的HTML,输出在Literal控件上面


精彩图集

赞助商链接