473,851 Members | 2,207 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Hiding and Showing Columns in the DataGrid Control...

The DataGrid allows you to make columns visible or invisible on demand
- even edit and other special columns. This article will show you how
it is done.

Some developers have reported problems controlling the visibility of
columns in the DataGrid control. The problem usually comes down to one
fact. The DataGrid has a property called AutoGenerateCol umns. The
default value is "True". This means that when AutoGenerateCol umns is
set to True, the DataGrid will pull its column headings straight from
the column names of the database table. If you allow this to happen
you cannot control the visibility of the columns. You must use
asp:BoundColumn s and specify the HeaderText and Datafield properties
in your DataGrid setup. This relatively simple change allows you
accomplish the hiding and showing of columns as you wish. It also
works with Edit and other special columns as you will see.

First, lets look at the html code in our .aspx page. Immediately below
the
tag we have two buttons and set OnClick event handlers to two
subroutines which will do the work of hiding and showing the
appropriate columns in our code-behind file. In the DataGrid code,
notice that AutoGenerateCol umns is set to "False". Also notice that we
have used asp:BoundColumn s to set our HeaderText and DataFields. I
have also set the Visible property to false so that nothing but the
CompanyName column will be shown at startup. I have also added an Edit
column although I did not wire it up to actually do any editing (the
copy of the Customers table in the Northwind database I am using is
readonly anyway). After the bound columns are some other datagrid
properties just to make the grid look good.







AutoGenerateCol umns="False"
BorderColor="#9 99999"
BorderStyle="No ne"
BorderWidth="1p x"
BackColor="Whit e"
CellPadding="3"
GridLines="Vert ical">







Now for the code-behind file which is shown in two parts. The first
part displayed below is just the usual page_load event which calls a
"BindTheDat a" routine to actually get the data from the Customers
table. All of this should be self explanatory.

Imports System.Data
Imports System.Data.Sql Client
Imports System.Configur ation

Public Class ShowHideCols : Inherits System.Web.UI.P age
Protected btnShow As System.Web.UI.W ebControls.Butt on
Protected btnHide As System.Web.UI.W ebControls.Butt on
Protected dtgCusts As System.Web.UI.W ebControls.Data Grid

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
If Not IsPostBack Then
BindTheData
End If
End Sub

Sub BindTheData
Dim objConn As SqlConnection
Dim objCmd As SqlCommand
objConn = New SqlConnection(C onfigurationSet tings.AppSettin gs("NorthwindCo nnection"))
Dim strSql As String
strSql = "SELECT Top 10 CompanyName, ContactName, ContactTitle,
City, Country, Phone FROM Customers"
objCmd = New SqlCommand(strS ql, objConn)
objConn.Open
dtgCusts.DataSo urce = objCmd.ExecuteR eader()
dtgCusts.DataBi nd()
objConn.Close()
objConn.Dispose ()
End Sub
Lastly comes our two subroutines to handle the showing and hiding of
the columns in the grid other than Company Name. Since Company Name is
Column(0), these routines use a simple For...Next loop to cycle
through the remaining columns setting the visible property to true or
false as appropriate.

Sub ShowDetails(sen der As System.Object, e As System.EventArg s)
Dim intCounter As Integer
For intCounter = 1 to dtgCusts.Column s.Count - 1
dtgCusts.Column s(intCounter).V isible = True
Next
End Sub

Sub HideDetails(sen der As System.Object, e As System.EventArg s)
Dim intCounter As Integer
For intCounter = 1 to dtgCusts.Column s.Count - 1
dtgCusts.Column s(intCounter).V isible = False
Next
End Sub

End Class
There you have it. A simple way to control the visible property of
your DataGrid columns.
AMBER [MCSD.NET MCAD.NET] http://www.dedicatedsolutions.co.uk
Nov 17 '05 #1
1 3389
>If you allow this to happen
you cannot control the visibility of the columns. You must use
asp:BoundColumn s and specify the HeaderText and Datafield properties
in your DataGrid setup.


This is not correct at all. Hiding autogenerated columns is easily
accomplished in the itemdatabound/created event handler by setting the
Cell's visible property to false.

Microsoft discourages developers from using the autogenerated feature except
for prototyping. I believe this to be a flawed recommendation on their part,
coupled to the fact that it is on by default. Developers should not fear the
autogenerate feature of a datagrid because it is very powerful, contains
most if not all the power of bound columns and results in a faster more
efficient datagrid render than if bound columns were used. The false premise
that microsoft builds on is that you do not have full control of the
datagrid when autogenerated columns is used. This is absolutely false.
Nov 17 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2228
by: c.anandkumar | last post by:
Hi All - I have some problems getting a small piece of javascript working correctly for Firefox. Here is what I am trying to do - 1. I have a form (like a search form) 2. I have many groups of searchable fields in the fields 3. Each group can be expanded/collapsed by clicking on a link "(Fewer|More) Options" which sits right next to the group title.
2
2134
by: Kevin | last post by:
Hi Al Can someone tell me how to hide colums in a datagrid. I have a one datagrid that is a master and child and I would like to hide specific columns, how do I do this TI Kevin
1
5575
by: Udi | last post by:
Hi everyone! I have a major problem with the DataGrid control for the Windows Form! I am using the DataAdapter to get data from Sql Server 2000 DataBase and populating a DataGrid with the Table i got. The problem is that i dont want to see all the table columns in the DataGrid, only some of it, how can i hide those unwanted columns? I cannot just not SELECTing it because i need to Update and Insert... Remember that i am using the...
2
2633
by: MrNobody | last post by:
I found some tutorial which had the following example for hiding columns in a DataGrid: http://samples.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/aspplus/samples/webforms/ctrlref/webctrl/datagrid/datagrid7.src&file=CS\datagrid7.aspx&font=3 The problem is, I have no "Columns" property on my DataGrid! I'm using Visual C# .NET IDE, which has version 1.1 of the framework. Do I need a more advanced version of the framework?
2
1554
by: Peter Rilling | last post by:
Okay, I know that the DataKeyField property of a DataGrid is supposed to allow me to define a field which will not be displayed. The values in that column end up in the DataKeys collection. My problem is that the column is still being rendered. I even tried the sample in the MSDN library for the DataKeyField and the column is showing. I though that this was supposed to give me the ability to hide the key column. Is there anything else...
1
840
by: Amber | last post by:
The DataGrid allows you to make columns visible or invisible on demand - even edit and other special columns. This article will show you how it is done. Some developers have reported problems controlling the visibility of columns in the DataGrid control. The problem usually comes down to one fact. The DataGrid has a property called AutoGenerateColumns. The default value is "True". This means that when AutoGenerateColumns is set to True,...
0
1086
by: klynn | last post by:
I queried a series of fields from a database and passed into a datatable. Then bound this to a datagrid. I need to hide 2 of the colums. This doesnt seem to be working the standard way. (with datagrid columns hide). When I query for number of columns in datagrid I always get 0 no matter what, even after showing all the columns. I must dynamically build the table after page post (I pass in parameters to define the table I'll be querying) so...
9
3198
by: tshad | last post by:
I have a datagrid that I want to add a new column to. This column will only be visible under certain conditions. So I want to set the column visible=false. Then when the right condition happens to change it to visible=true. You can't do that with a bound column (no ID), but you can create a templatecolumn with a label. To make these visible, I am going through each datagriditem and making them visible after I have bound the data to...
0
2602
by: Bob Davies | last post by:
Hi I have a webservice that retrieves data from a database, this is then returned to the calling client application built in windows forms within a dataset, however upon attempting to create tablestyles to format any of the columns within the datagrid, the exception "Can-not parent objects created on one thread to objects created on another" or words to that effect. I'm not too sure if what I said make sense, but i will add details to...
5
3703
by: Rich | last post by:
I have a datagrid that uses a dataview object for its datasource. The dataview contains a unique row identifier column. I don't want to display this column in the datagrid. I need the unique row Identifier column so that I can run updates on the SqlAdapter object. Is there a way to hide this column from the datagrid? Dim dv1 As New DataView(ds.Tables("tbl1")) dv1.AllowNew = False dgr1.DataSource = dv1 '--dgr1 is the datagrid
0
9896
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11017
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10670
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10352
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9505
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5736
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5933
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4143
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3178
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.