I desperately needed to hide/show some columns of my GridView since I was showing the same user control to different groups of users and they didn’t need to see the same information. The columns’ property Visible takes Boolean value true/false but doesn’t take the value of a user function (throws error). Therefore, I searched and found alternate suggestion of hiding columns in the code view by using the columns’ indexes; like the following:
grid0.Columns[0].Visible = false;
However, this approach has problem because if the column order is changed or a column is deleted then it will not work properly. As a result, I needed codes to be able to use the name/header text of the column to hide it. With the help of one of my colleagues we were able to manipulate some code found in online to do our job. Here it is:
Common.ShowThisColumn("Command", gvAttachments, true);//default is hide public static void ShowThisColumn(string columnName, GridView gv, bool show) // can be reused for any GridView { int index = GetGridViewColumnIndex(gv.Columns, columnName); if (index > -1) gv.Columns[index].Visible = show; } public static int GetGridViewColumnIndex(DataControlFieldCollection columns, string DataColumnName) { foreach (DataControlField field in columns) { if (field is System.Web.UI.WebControls.BoundField) { if (((BoundField)field).DataField == DataColumnName) return columns.IndexOf(field); } else if (field is System.Web.UI.WebControls.TemplateField) { if (((TemplateField)field).HeaderText == DataColumnName) return columns.IndexOf(field); } } return -1; }
0 Comments