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

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

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
C# Code [http://www.xueit.com] private void SetupShowHideColumns(GridView gridView, Literal showHideColumnsLiteral){ StringBuilder sb = new StringBuilder(); sb.Append( " div class=\"showHideColumnsCon

C# Code [http://www.xueit.com]
private void SetupShowHideColumns(GridView gridView, Literal showHideColumnsLiteral)
{
    StringBuilder sb = new StringBuilder();

    sb.Append("<div class=\"showHideColumnsContainer\">");
    sb.Append("<select id=\"");
    sb.Append(gridView.ClientID);
    sb.Append("_showCols\" onchange=\"javascript:ShowCol('");
    sb.Append(gridView.ClientID);
    sb.Append("', this.value);\" style=\"display:none;\">");
    sb.Append("<option>- Show Column -</option></select></div>");

    showHideColumnsLiteral.Text = sb.ToString();
}

    在数据绑定到GridView之后,其余的工作由ShowHideColumns.js中的javascript来完成.当列头的hyperlink被点击的时候后,它将会传递GridView的名字,列的索引和列名给HideCol方法,这个方法能找到这一列的每个单元格,每个单元格的将添加display:none样式,用来隐藏这一列.

   当选择"Show Column"中的选项后,Javascript方法ShowCol将会被调用,它将移除每个单元格的display:none样式,这一列将会被再次显示.

在服务端显示/隐藏GridView的列

服务端的例子将通过RowCreated事件给每个列头添加一个负号,这次是使用LinkButton控件.设置CommandName和CommandArgument属性,这样当通过LinkButton引发RowCommand事件时,相关的列都可以隐藏。以前隐藏的列索引存储在一个List<int>中,这些列在建立时,将会被隐藏的。

C# Code [http://www.xueit.com]
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    // For the header row add a link button to each header
    // cell which can execute a row command
    if (e.Row.RowType == DataControlRowType.Header)
    {
        // Loop through each cell of the header row
        for (int columnIndex = 0; columnIndex < e.Row.Cells.Count; columnIndex  )
        {
            LinkButton hideLink = new LinkButton();
            hideLink.CommandName = "hideCol";
            hideLink.CommandArgument = columnIndex.ToString();
            hideLink.Text = "-";
            hideLink.CssClass = "gvHideColLink";
            hideLink.Attributes.Add("title", "Hide Column");

            // Add the "Hide Column" LinkButton 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);
            }
        }
    }

    // Hide the column indexes which have been stored in hiddenColumnIndexes
    foreach(int columnIndex in hiddenColumnIndexes)
        if (columnIndex < e.Row.Cells.Count)
            e.Row.Cells[columnIndex].Visible = false;
}

在SetupShowHideColumns 方法中创建"Show Columns"下拉菜单,以前被隐藏的列名被添加到"Show Columns"下拉菜单选项中。


精彩图集

赞助商链接