Hide columns in a Datagrid (AutoGenerated and Dynamic)
DataGrid is a very powerful tool in the .Net toolbox. There are lots of features offered by it.
We most often use the column index to hide columns that we don't need the user to see. This poses a problem, if the index changes.
e.g. myGrid.Columns[1].Visible = false; //this will hide the second column
But, the problem arises if the dataset returned is changed. That is, if the dataset is changed, so as to return some other column in that index, then it would be always hidden. So evey time, we need to modify the
column index in the code.
A quick solution to such a problem is to use the
i) DataGridColumn.HeaderText property of the DataGrid
if the DataGrid has auto-genereated columns
ii) Use the Cells[index]
property that is obtained by looping through the DataGridItms in the Controls Collection.
The HideColumn function below will serve
this purpose.
/* HideColumn method takes two parameters.
ColName = Name of the column to hide
ColumnType = "Auto" - for autogenerated columns, "Others"
- for other types (Button, Hyperlink, Template, Bound)
e.g. HideColumn("emp_sal","Auto");
HideColumn("emp_sal","Others");
*/
private void HideColumn(string ColName, string ColumnType)
{
/* This is for Bound, Template, HyperLink or Button Columns*/
if (ColumnType == "Others"){
foreach(DataGridColumn col in grid.Columns){
if (col.HeaderText == ColName){
col.Visible
= false;}}}
else
/* This is for AutoGenerated Columns. Loops through the Row-wise Data */
{
int iLoc = 0;
bool chk = false;
foreach(DataGridItem it in grid.Controls[0].Controls)
{
for ( int iTemp = 1;iTemp <= grid.Items[0].Cells.Count;iTemp++)
{
if (it.Cells[iTemp-1].Text == ColName)
{
it.Cells[iTemp-1].Visible
= false ;
iLoc
= iTemp-1;
chk
=true;
continue;
}
if (chk == true)
{
it.Cells[iLoc].Visible
= false;
}
}
}
}
}
By [)ia6l0 iii Popularity (2813 Views)