Cannot reference non-visible cell value in gridview but it works in datagrid


I found one interesting thing just want to share with you all.


There is one difference between DataGrid and Gridview. During my .NET Fx1.1 time, I set the column visibility to false and still access that column through my code behind using code like e.cells[0].Text like that.

Now if you do the same thing with Gridview, it would return blank instead of value. Strange!!!

The reason I found after binging(because I like Microsoft J )


Basically, Microsoft has decided that hidden columns in DataGrids were almost always used to store primary keys of records, and that maintaining them in ViewState represented a security risk. Therefore, in the GridView object introduced in v2, hidden columns have been removed from ViewState by default, which is why the columns themselves are still there (otherwise you couldn't reference them in the CodeFile), but their values are blank.


The work around for Gridview is to use following way…..


grdObject.DataSource = <datasource>;

grdObject.Columns[0].Visible = true;

grdObject.DataBind();

grdObject.Columns[0].Visible = false;


or you can take HTML hiddenfield and make it runat=server and set the value using EVAL. Then you can reference this control from code-behind.