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.

2 comments:

  1. 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; }

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

    ReplyDelete