Hi Akhter,
In your Gridview there is no columns defined as AutoGenerateColumns is set to true.
So you have perform For Loop on GridView header and data rows to hide cells.
Please refer below sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="true">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<br />
<asp:Button Text="Submit" ID="btnSubmit" OnClick="Submit" runat="server" />
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 CustomerId, CompanyName, ContactName, Country FROM Customers", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
this.gvEmployees.DataSource = dt;
this.gvEmployees.DataBind();
}
}
}
}
}
protected void Submit(object sender, EventArgs e)
{
this.gvEmployees.HeaderRow.Cells[0].Visible = false;
for (var i = 0; i < this.gvEmployees.Rows.Count; i++)
{
this.gvEmployees.Rows[i].Cells[0].Visible = false;
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 CustomerId, CompanyName, ContactName, Country FROM Customers", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Me.gvEmployees.DataSource = dt
Me.gvEmployees.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub Submit(ByVal sender As Object, ByVal e As EventArgs)
Me.gvEmployees.HeaderRow.Cells(0).Visible = False
For i = 0 To Me.gvEmployees.Rows.Count - 1 Step 1
Me.gvEmployees.Rows(i).Cells(0).Visible = False
Next
End Sub
Screenshot