Hiding a Column in an ASP.NET GridView

Two of the many ways you can hide a column in an ASP.NET GridView are as follows:

1. Set the GridView column’s 'Visibility' property to 'False'. However in this case, GridView will not bind the data to the GridView. So if you want to use that hidden column (like a Master-Detail scenario), you won't be able to do it.

You can also hide the column programmatically in the RowDataBound event


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)


{


    e.Row.Cells[0].Visible = false;


}




VB.NET


Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)


    e.Row.Cells(0).Visible = False


End Sub




2. Use the OnRowCreated event which gets called after the data is bound

C#


protected void GridView1_OnRowCreated(object sender, GridViewRowEventArgs e)


{


  e.Row.Cells[0].Visible = false;


}




VB.NET


protected void GridView1_OnRowCreated(object sender, GridViewRowEventArgs e)


{


  e.Row.Cells[0].Visible = false;


}




Using this way, you can use a hidden column's data even if it is hidden.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

Try this to use the rendered data:

protected void grdOrgs_RowDataBound(object sender, GridViewRowEventArgs e)
{ ...
e.Row.Cells[2].CssClass = "Hdn";
}
---------- and in CSS:
.Hdn { display:none; }

Sughus said...

Thanks for this post, it save a lot of time.