Friday, May 27, 2005
Hiding Columns in a DataGrid
I needed to be able to let the user hide and unhide columns from the DataGrid control. This was pretty easy, as I just added a LinkButton to each of the HeaderTemplates:
To allow someone to show the column again, I just created a DropDownList of all of the hidden columns, which can be found by looping through MyDataGrid.Columns and adding a column to the list if .Visible = False. Since I not only provided a HeaderTemplate for each column, but also specified the HeaderText, I can use the .HeaderText property in the loop to add the name of the column to the DropDownList.
<SUP><asp:linkbutton runat="server" CommandArgument="3"where the CommandArgument is set to be the column's index (starting at 0). Then inside the MyDataGrid_ItemCommand function, I just set MyDataGrid.Columns(e.CommandArgument).Visible = False when e.CommandName = "HideColumn".
CommandName="HideColumn">x</asp:linkbutton></SUP>
To allow someone to show the column again, I just created a DropDownList of all of the hidden columns, which can be found by looping through MyDataGrid.Columns and adding a column to the list if .Visible = False. Since I not only provided a HeaderTemplate for each column, but also specified the HeaderText, I can use the .HeaderText property in the loop to add the name of the column to the DropDownList.