Programmatically Hiding Auto-Generated Columns by Name
By: Patrick Philippot | Created: 2003-05-16 | Last Updated: 2003-05-17



The Origins of this FAQ
This FAQ is authored by Patrick Philippot as a newgroup post to the microsoft.public.dotnet.framework.aspnet.datagrid newsgroup on May 16th, 2003. It is reprinted with the author's permission.

This FAQ examines how to programmatically hide a DataGridColumn when the DataGrid's columns are automatically generated (that is, the DataGrid's AutoGenerateColumns property is set to the default, True.)

I first thought this was an easy task. My mistake. Since a lot of people seem to have had the same problem, here's the solution that I found. This workaround assumes that you know the name of the column(s) that you want to hide. Remember that you can't access an auto-generated column directly by name in a Web form DataGrid. You can get control on the columns visibility if you set AutoGenerateColumns to False but in many cases, this is neither possible nor wanted. Here we go...

  1. In the DataGrid's declaration, add the following attribute: OnItemDataBound="Item_Bound"
  2. Create a handler for this event
    void Item_Bound(Object sender, DataGridItemEventArgs e) { DataView dv = MyDataGrid.DataSource as DataView; DataColumnCollection dc = dv.Table.Columns; e.Item.Cells[dc.IndexOf(dc["field_name"])].Visible = false; }
    C#

     

The documentation states that the column order in the DataGrid is the same as in the underlying DataSource. So it's just a matter of retrieving the index of the target column in the Dataview's underlying table (by using the IndexOf method) and then set the Visible property of the corresponding cell to false.

It is assumed here that the DataSource is a DataView but this would work similarly with another type of DataSource as long as you can access the table(s) used in the DataGrid. Also, this is not canonical OOP but we have no choice here.


Home | FAQs | Articles | About | Buy the Book!

Copyright 2006, Scott Mitchell. All Rights Reserved.