Last post Mar 30, 2006 01:46 AM by craigt-from-atl
Mar 28, 2006 05:41 PM|craigt-from-atl|LINK
I would like to show/hide columns of my GridView based on user events.
When the user clicks on a specific button, I would like to show/hide certain columns based on the column's name. I can't seem to get this working. When I do GridViewName.Columns, it only allows me to use an index and not a string to find the column.
I can easily show/hide the columns based on the index of the column, but I would rather not hardcode index values in my application. If I were to add or remove a column at a later date, I would have to go back through the code to adjust the indexes.
Mar 29, 2006 04:58 AM|ResinMC|LINK
Use the following method to retrieve the column index of the column you want to hide:
int GetColumnIndex(GridView grid, string colName)
int intCount = 0;
foreach (DataColumn col in grid.Columns)
if (col.ColumnName.ToLower().Trim() == colName.ToLower().Trim())
From there, you can hide your column by calling the following:
GridView1.Columns[GetColumnIndex(GridView1, "column name here")].Visible = false;
Mar 29, 2006 02:02 PM|craigt-from-atl|LINK
Ah.. . .
Wish it took less code, but that will work! Thanks for your tip!
Mar 30, 2006 01:37 AM|craigt-from-atl|LINK
Unable to cast object of type 'System.Web.UI.WebControls.BoundField' to type 'System.Data.DataColumn
Getting it on the "if (col.ColumnName.ToLower().Trim() == colName.ToLower().Trim())" line.
Trying to figure out a way around this one, but any suggestions would be welcome. :)
Mar 30, 2006 01:46 AM|craigt-from-atl|LINK
private int GetColumnIndex(ref GridView grid, string colName)
int intCount = 0;
foreach (DataControlField col in grid.Columns)
if (col.SortExpression.ToLower() == colName.ToLower())
I just had to make sure each column had a SortExpression on it. So it works, but I'm just not sure if it's an approved method. :)