Tuesday, December 18, 2007

Hiding and Showing Columns in the Data Grid

Some programmers have face the problem controlling the visibility of certain column in the Data Grid control. In this post, I will show you how to hide and show certain column in the data grid.

Data grid control has a property called AutoGenerateColumns. By default, its values is set to True, which will contain all of the column names of the data set as you bind it with the data set. If you set the AutoGenerateColumns to True, then you would not be able to control the visibility of the columns.

You can either use asp:BoundColumn or asp:TemplateColumn. For asp:BoundColumn, you need to specify the HeaderText and its DataField. Here is a tiny part of html sample code:
<asp:BoundColumn DataField="COUNTRY" HeaderText="Country">
    <HeaderStyle Font-Size="11px" >
    </HeaderStyle>
    <ItemStyle Font-Size="10px" >
    </ItemStyle>
</asp:BoundColumn>

<asp:BoundColumn DataField="ADDRESS" HeaderText="Address">
    <HeaderStyle Font-Size="11px" >
    </HeaderStyle>
    <ItemStyle Font-Size="10px" >
    </ItemStyle>
</asp:BoundColumn>

Or with asp:TemplateColumn, you need to specify its HeaderText and bind value into it. For example:
<asp:TemplateColumn HeaderText="Country">
    <HeaderStyle Font-Size="11px" >
    </HeaderStyle>
    <ItemStyle Font-Size="10px" >
    </ItemStyle>
    <ItemTemplate>
        <%# Container.DataItem("COUNTRY")%>
    </ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn HeaderText="Address">
    <HeaderStyle Font-Size="11px" >
    </HeaderStyle>
    <ItemStyle Font-Size="10px" >
    </ItemStyle>
    <ItemTemplate>
        <%# Container.DataItem("ADDRESS")%>
    </ItemTemplate>
</asp:TemplateColumn>

From the html sample code as above, now you can control the visibility of the columns easily. In your .aspx page, you can add in two buttons (btnShow and btnHide) and set OnClick event handlers to them which will do the work of hiding and showing the column “Address” in code behind file.
Private Sub btnShow_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShow.Click
      dg.Columns(1).Visible = True
End Sub

Private Sub btnHide_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHide.Click
      dg.Columns(1).Visible = False
End Sub

Here it is, a simple way to control the visibility of your data grid’s columns. Good luck.

0 comments:

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template