Programmatically Hiding ASP.NET Grid View Column.

Recently I have been to and found that lots of people are finding solution for hiding the Grid View column so I though it will be a good Idea to write a blog post. In this post I will explain how we can hide GridView Column programmatically. So let’s take same example that I have taken in previous post.

Hide ASP.NET GridView Column:

So let’s take  a simple example. I am going to bind a grid with list of Employee class and then on a button click I am going to hide the first column of grid. Following is a HTML code for that.
    <asp:Button runat="server" Text="Hide Column" ID="btnHideColumn" OnClick="btnHideColumn_Click"/>
        <asp:GridView runat="server" ID="employeeGrid" AutoGenerateColumns="False">
                <asp:BoundField HeaderText="Employee Id" DataField="EmployeeId"/>
                <asp:BoundField HeaderText="First Name" DataField="FirstName"/>
                <asp:BoundField HeaderText="Last Name" DataField="LastName"/>

In the above code I have taken a grid view and I have taken a button to hide the Employee Id column. Here I have taken Employee class like following.
public class Employee
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

Following is a code for binding GridView.
protected void Page_Load(object sender, EventArgs e)
    if (!Page.IsPostBack)
public void BindGridView()
    var employees = new List<Employee>()
            new Employee {EmployeeId = 1, FirstName = "Jalpesh", LastName = "Vadgama"},
            new Employee {EmployeeId = 2, FirstName = "Vishal", LastName  ="Vadgama"},
            new Employee {EmployeeId = 3, FirstName = "Teerth", LastName = "Vadgama"}
    employeeGrid.DataSource = employees;

As you can see in the above code I have created a method to bind GridView and called that method in page_load event.  In BindGridView method I have created a list of employee class and then bind that list to GridView. On the click of btnHideColumn I have written code to hide column like following.
protected void btnHideColumn_Click(object sender, EventArgs e)
    employeeGrid.Columns[0].Visible = false;

That’s it. Let’s run the example.

Hide Column in ASP.NET Gridview

Now once you click Hide Column It will look like following.

That’s it. Its very easy. Hope you like it. Stay tuned for more..


Popular posts from this blog

Creating PDF with ASP.Net MVC and RazorPDF

Horizontal and vertical scrollbar in HTML5 and CSS3

How to create Rest API(Web API) with ASP.NET Core 1.0