Hide GridView Columns In ASP.NET

This example shows how to Hide GridView Columns in normal mode in asp.net and set them to visible when gridview is in edit mode. I am hiding the ID column when gridview loads and setting this column to visible when user clicks on the edit link button.

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

Hide GridView Columns In ASP.NET


<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")%>'/>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtID" Visible="true" runat="server"
             Text='<%#Eval("ID")%>'/>
</EditItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'/>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtName" Visible="true" runat="server"
             Text='<%#Eval("Name")%>'/>
</EditItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" 
           Text='<%#Eval("Location")%>'/>
</ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="txtLocation" Visible="true" runat="server"
             Text='<%#Eval("Location")%>'/>
</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>


We need to write following code to hide columns in RowDataBound event

C# CODE
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();
    }

VB.NET
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 'Check whether gridview is in edit mode or nor 
 If GridView1.EditIndex >= 0 Then
  Return
 End If
 'Check row state of gridview whether it is data row or not
 If (e.Row.RowState = DataControlRowState.Normal OrElse e.Row.RowState = DataControlRowState.Alternate) AndAlso (e.Row.RowType = DataControlRowType.DataRow OrElse e.Row.RowType = DataControlRowType.Header) Then
  'Now set the visibility of cell we want to hide to false 
  e.Row.Cells(1).Visible = False
 End If
End Sub

Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
 GridView1.EditIndex = e.NewEditIndex
 GridView1.DataBind()
End Sub


Download Sample Code


16 comments:

  1. Thanx i was looking for this , Google brought me here

    ReplyDelete
  2. i want to download source code of this artical

    ReplyDelete
  3. @himanshu :

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

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

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

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

    ReplyDelete
  7. 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

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

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

    ReplyDelete
  10. Thank your for your solution amit !!

    ReplyDelete
  11. And it will also hide the column header?

    ReplyDelete
  12. 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

    ReplyDelete
  13. hello i want to know that how to bind controls to the gridview

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

    ReplyDelete