介绍
本文演示如何允许用户根据需要显示或隐藏GridView
列,如果GridView
中有些列不是所有用户都必需的,那么这非常有用;对于报表类型页,用户还可以灵活选择打印的GridView
列。
背景
RowCreated
和ItemDataBound
事件允许你以多种方式插入HTML,CSS和JavaScript来增强GridView
控件。
样例应用程序
下面是显示四列的基本GridView
:
通过单击列标题中的减号,用户可以隐藏列;在这种情况下,"Id"列被隐藏:
以下是Id列隐藏的同一页的打印预览:
本文将演示两种显示和隐藏GridView
列的方法,一种在客户端,另一种在服务器端。
在客户端显示/隐藏GridView列
CSS类也用于增加减号的大小,在创建每个DataRow
时,将向每一行添加一个Id,以便JavaScript可以识别它。
protectedvoid 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 methodif (e.Row.RowType == DataControlRowType.Header) { // Loop through each cell of the rowfor (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 labelif (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 idif (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()); }
"显示列"下拉列表的HTML在SetupShowHideColumns
方法中生成,并写出到Literal
控件中。
privatevoid 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文件完成,单击列标题中的超链接时,它将GridView
name,column index和column name传递给HideCol
table方法,通过向单元格中添加display:none ;
样式,隐藏列来修改每个单元格的样式。
当从"显示列"下拉列表中选择一个选项时,将调用ShowCol
JavaScript方法,该方法将从display:none ;
列中删除每个单元格。