June 7, 2011

How to hide an ASP.NET Gridview Column?

For example , You d like to hide the first column (ID columns) that you can use its value


<columns>
    <asp:boundfield datafield="ID" headertext="" />
    <asp:boundfield datafield="Name" headertext="Name" />
    <asp:boundfield datafield="Date" headertext="Date" />
<asp:boundfield datafield="Country" headertext="Cuontry" />
</columns> 

1- Add this CSS class

<style type="text/css">
    .hiddenCol    {
        display:none;
    }
    
</style>


2-Add it to the column you like to hide


<asp:boundfield datafield="ID" headertext=""  
             itemstyle-cssclass="hiddenCol" />


3-In server code , implement the row created event


protected void GridView_RowCreated(object sender,
GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         e.Row.Cells[0].CssClass = "hiddenCol";
     }
     else if (e.Row.RowType == DataControlRowType.Header)
     {
         e.Row.Cells[0].CssClass = "hiddenCol";
     }
}