Hide GridView Columns In ASP.NET

This example shows how to hide columns of gridview in normal display mode and set them to visible when gridview is in edit mode

here i am hiding the ID column when gridview loads in normal mode and setting this column to visible when user clicks on the edit link button of gridview

For this i am using ObjectDataSource to populate the grid and hiding the columns in RowDataBound Event of gridview








<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;<br />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="ObjectDataSource1"
OnRowDataBound="GridView1_RowDataBound"
OnRowEditing="GridView1_RowEditing" >
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID"
runat="server"
Text='<%#Eval("ID")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtID" Visible="true"
runat="server"
Text='<%#Eval("ID")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName"
runat="server"
Text='<%#Eval("Name")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtName" Visible="true"
runat="server"
Text='<%#Eval("Name")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server"
Text='<%#Eval("Location")%>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtLocation"
Visible="true"
runat="server"
Text='<%#Eval("Location")%>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1"
runat="server"
InsertMethod="Insert"
OldValuesParameterFormatString="original_{0}"
SelectMethod="GetData"
TypeName="DataSet1TableAdapters.TestTableAdapter"
UpdateMethod="UpdateQuery">
<InsertParameters>
<asp:Parameter Name="ID" Type="Decimal" />
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Location" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Location" Type="String" />
<asp:Parameter Name="ID" Type="Decimal" />
</UpdateParameters>
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>

And the code behind for this goes like this
We need to write code to hide columns in RowDataBound event

public protected void GridView1_RowDataBound
(object sender, GridViewRowEventArgs e)
{
//Check whether gridview is in edit mode or nor 
if (GridView1.EditIndex >= 0)
{ return; }
//Check row state of gridview whether it is data row or not
if ((e.Row.RowState == DataControlRowState.Normal
|| e.Row.RowState == DataControlRowState.Alternate)
&& (e.Row.RowType == DataControlRowType.DataRow
|| e.Row.RowType == DataControlRowType.Header))
{
//Now set the visibility of cell we want to hide to false 
e.Row.Cells[1].Visible = false;
}
}
protected void GridView1_RowEditing
(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
}


Download the sample code attached



If you like this post than join us or share

16 comments:

Anonymous said...

Thanx i was looking for this , Google brought me here


himanshu said...

i want to download source code of this artical


amiT jaiN said...

@himanshu :

You can download the code now, i've fixed the download link


ராமகிருஷ்ணன் த said...

your posts are nice.
how to set readonly to id field in gridview when editing


Anonymous said...

студент видео онлайн http://free-3x.com/ малолетние порно фотомодели free-3x.com/ смотреть порно школа [url=http://free-3x.com/]free-3x.com[/url]


Anonymous said...

порно школьниц смотреть бесплатно видео
порево порно
видеоролики эротика просмотр
видео занятие сексом
порно мувики бесплатно
скачать порнофильм taboo бесплатно
порно жёсткое взрослые
эротическое видео ролики скачать
московский секс
пизда рвётся фото


christopher said...

hi

here u have check for Edit mode ,Y?

Please let me know

and i have another question for sqlserver

i have table ABC

in that

Vehiclename driver
=====================
Car 1,2
Car 1,3,5
Car 1,2,3,4
Scooter 2,4,6
Scooter 2


now i want result like this

Vehiclename Driver
=======================
Car 1,2,3,4,5
Scooter 2,4,6

Please give query for this


Anonymous said...

Hello. And Bye.


Anonymous said...

Да уж… Жизнь – как вождение велосипеда. Чтобы сохранить равновесие ты должен двигаться.


Anonymous said...

how to display image in gridview after retrieving binary data of an image file which is stored in the database


Anonymous said...

Thank your for your solution amit !!


Anonymous said...

And it will also hide the column header?


amiT jaiN said...

@Above : Yes, it Will


Anonymous said...

please tell me does windows xp sp2 support asp.net 4.0 ? does asp.net 4.0 work successfully on windows xp sp2 ? My email id is : hiralvyas1986@yahoo.in


Anonymous said...

hello i want to know that how to bind controls to the gridview


amiT jaiN said...

@Above: Please refer GridView Examples in ASP.NET 2.0 3.5 to know how to bind controls in GridView