KeyLimeTie Blog

Hide DataGrid columns when they are dynamically generated

By Brian Pautsch – 3/6/2006 11:41:54 PM. Posted to Code Snippets.

In a recent project I was working on, I needed to hide DataGrid columns in a table where the columns are dynamically generated. I thought I might be able to do it after binding to the DataGrid or during the DataBinding event, but no luck. It turns out you have to hide the cells in each row (including the header and footer) during the DataGrid's ItemDataBound event. By the way, in my example, I have an 'Edit' column in the first columns always...so remember that when you implement this solution.

1//Private constants/variables
2private const int mintNumColsToShow = 4;
3private int mintColCt = 0;
4
5//In some method...get data and bind to DataGrid
6objDataSvc = new DataSvc();
7DataTable objDT = null;
8objDT = objDataSvc.GetData();
9mintColCt = objDT.Columns.Count;
10dgResults.DataSource = objDT;
11dgResults.DataBind();
12
13//DataGrid's ItemDataBound event
14private void dgResults_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
15{
16 //Only show first n columns (including 'Edit')
17 if (mintColCt > mintNumColsToShow)
18 {
19  for (int intCt = mintNumColsToShow + 1; intCt <= mintColCt; intCt++)
20  {
21   e.Item.Cells[intCt].Visible = false;
22  }
23 }
24}

Comments

On 1/8/2010 Brian Pautsch said:
GH,

On 1/8/2010 GH said:
How would you hide a column if the sql (or Dataset/Datareader) does not include that column?

On 1/8/2010 Elaine said:
What's that rorschach thing on your business card? Looks like an upside down picture of a pony biting a buffalo.

On 4/11/2008 Gaurav said:
it works...

On 10/19/2006 Brian Pautsch said:
The code isn't supposed to hide the headers and it just hides any columns after the value specified in "mintNumColsToShow". To hide specific columns, see the comment I left on "10/4/2006".

On 10/19/2006 Robjay said:
When I use this, it shifts some cells over but doesn't target the specific column - which is what I would like. i.e. the headings still display

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe