Hide Gridview Column (incl Header) if contains no data

I have a gridview but frequently some of the cells in a row are blank, if this is the case for all the rows of returned data i would like to hide the entire column. Any ideas?

 I came up with:

 

        For i As Integer = 0 To GridView4.Rows.Count - 1
            Dim row As GridViewRow = GridView4.Rows(i)
            If row.Cells(i).Text = "" Then
                row.Cells(i).Visible = False
            End If
        Next
 

But it doesnt work at all : (
0
stephen
4/30/2009 11:24:09 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

4 Replies
765 Views

Similar Articles

[PageSpeed] 58

Here's a quick example:

ASPX 

<%@ page language="VB" autoeventwireup="false" codefile="1417473.aspx.vb" inherits="MyPosts_GeneralASPNET_DataPresentationControls_1417473" %>

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:gridview id="GridView1" runat="server" autogeneratecolumns="false">
        <columns>
            <asp:boundfield datafield="Column1" headertext="Column1" />
            <asp:boundfield datafield="Column2" headertext="Column2" />
            <asp:boundfield datafield="Column3" headertext="Column3" />
        </columns>
    </asp:gridview>
    </form>
</body>
</html>

CODE-BEHIND 

Partial Class MyPosts_GeneralASPNET_DataPresentationControls_1417473
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Me.IsPostBack Then
            GridView1.DataSource = Me.MakeList( _
               New With {.Column1 = 1, .Column2 = DBNull.Value, .Column3 = 1}, _
               New With {.Column1 = 2, .Column2 = DBNull.Value, .Column3 = 2}, _
               New With {.Column1 = 3, .Column2 = DBNull.Value, .Column3 = 3}, _
               New With {.Column1 = 4, .Column2 = DBNull.Value, .Column3 = 4}, _
               New With {.Column1 = 5, .Column2 = DBNull.Value, .Column3 = 5})
            GridView1.DataBind()
        End If
    End Sub

    Private Function MakeList(Of T)(ByVal ParamArray items() As T) As List(Of T)
        Return New List(Of T)(items)
    End Function

    Protected Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender
        Dim notEmpty As Boolean = False

        For Each row As GridViewRow In GridView1.Rows
            If row.Cells(1).Text &lt;&gt; "&nbsp;" Then
                notEmpty = True
            End If
        Next

        GridView1.Columns(1).Visible = notEmpty
    End Sub
End Class

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
4/30/2009 12:23:56 PM

If u want to hide column then why have u written this code 

row.Cells(i).Visible = False?? //it is making the cell visible false.
 
there must be something like  

 

GridView4.Column.Visible false //// u have to implement that.

Please mark as answer if it helped u!
0
kavita_khandhadia
4/30/2009 12:27:58 PM

First loop through all rows and columns and decide which all columns doesn't have value in all the rows.. and then set the visibility..

Try this code

Dim dataExist As New Hashtable
        'creating a hashtable entry for each columns and initialising it as there is no data for all columns
        For i As Integer = 0 To GridView1.Columns.Count - 1
            dataExist.Add(i, False)
        Next

        For Each row As GridViewRow In GridView1.Rows
            For i As Integer = 0 To GridView1.Columns.Count - 1
                If row.Cells(i).Text <> "" Then 'for a column if there is data we will mark it in the hashtable
                    dataExist(i) = True
                End If
            Next
        Next

        For Each key As Object In dataExist.Keys
            GridView1.Columns(key).Visible = dataExist(key)
        Next


If this post was useful to you, please mark it as answer.

ClientSideAsp.Net | Blog
0
anzer
4/30/2009 12:38:27 PM

 Hi Ed,,

i did the same thing as you did but more generic to make it work for all the columns...

@Kavita..

he needs to set the visibility of columns if there is no data present in all the the rows for that column...


If this post was useful to you, please mark it as answer.

ClientSideAsp.Net | Blog
0
anzer
4/30/2009 12:46:02 PM
Reply:

Similar Artilces:

i have work on gridview control.in that i have 3columns.name as subject,bookname,link. in this some link column data are very large.according to that data(no spaces in that data)gridview has changed.i
hi,i have work on gridview control.in that i have 3columns.name as subject,bookname,link. in this some link column data are very large.according to that data(no spaces in that data)gridview has changed.i want display half of the data and remaining display like this.(ex:http://ww.yahoo.com...........).how can i display like this,and one more thing is always the column size will constant. Try something like this: <asp:templatefield headertext="Link"> <itemtemplate> <asp:hyperlink id="HyperLink1" runat="server" navigateurl='<...

Data presentation control in another Data presentation control
 Hello,I want to make a menu with datalist or gridview control.Basically,the menu will be like this,Categories     Sub Categories.For example, for COMPUTING category there will be NOTEBOOKS DESKTOPS etc.There will be a image for CATEGORIES and linkbuttons with Subcategories.If I put a datalist inside a datalist and a link button inside the second datalist visually it satisfies my need.However,CommandArguments come from database to linkbutton.Andwhen one of these command buttons is cliked it must go to proper page.I dont know how to wrie an event_handler ,specifically, for...

Nested GridViews
Hello everyone, I've been searching for a solution on this for hours with no luck. Maybe i'm just making it harder than what it needs to be, but i'm at my wits end here.  I have two nested gridviews - one for showing "clients", and another for showing projects assiciated with said client. A client may not have any projects assigned though, so how do I just not show the client's name in the list if there are no projects associated with it? I'm binding both gridviews to a DataView, and i'm calling the function to bing the client gridview in ...

Is there a control that offers the same data presentation as a GridView, but allows users to copy and paste many rows/columns at once?
 Hi Is there a control that offers the same data presentation as a GridView, but allows users to copy and paste many rows/columns at once onto the grid? What I mean is some grid that 's as flexible as MS Excel grid for example.  Any suggestions will be very much appreciated.E The Repeater control is a highly customisable data presentation controlRohin.NET developerNever trust a computer you can't throw out a window. - Steve WozniakPlease remember to click on 'Mark as answer', if this post helped you......

how to hide column data but keep column header text
 Hello,i want to hide my column data programmatically (C#) but still keep the column and its header.Like if i have a column with header "Title". All the data in this column must not be visible.any suggestion? Thank you  If it is all the data in a given column, then one way of doing it, would be to change: SELECT A, B, C, TITLE FROM TABLEtoSELECT A, B, C, TITLE, '' AS TITLE2 FROM TABLE Duplicate the Title column and change the data that is displayed in the second to TITLE2. For those that are allowed to see the data, show the first, for those tha...

Gridview scrolling with Fixed Header
Hi   I want to keep the Headers fixed and  scroll the GridView . I am using the following the code.  <HeaderStyle HorizontalAlign="Left" ForeColor="Black" CssClass="Freezing" BackColor="#E0E0E0" />.Freezing { position:relative ; top:auto; /* top:this.offsetParent.scrollTop-1; */ /* top:expression(this.Parent.scrollTop); */z-index: 10; }  It works fine for Bound columns . It does not work for Dropdown columns. when i scroll the grid Dropdown box hides the Header text. My code is below.  <div class="&...

Issue with Template Columns & Bound Columns while updating the data in a GridView control
Hi, I'm facing the below problem (In general, ObjectDataSource is driving me crazy ! ) I have a simple gridview control and an ObjectDataSource is used to populate the grid. I'm trying to update a row and the corresponding tableadapter methods & stored procedure are in place. Each row has 2 checkboxes and 2 textboxes in edit mode. When the change the values in edit mode and hit update, the checkbox values changed are saved into the Database properly, whereas the textbox values are not being saved. If the textbox column is a bound column then the column is updated with <NULL> in...

binding a gridview to xmldatasource gives "The data source for gridview gridview1 did not have any properties or attributes from which to generate columns. Ensure that your data source has columns
Greetings!  I am new to asp.net forum so feel free to point me to the proper resources or forums.  I am using Visual Studio 2005.  I have a simple web page with a gridview control and an xmldatasource control.  I am getting the above error.  Can someone point out why I am getting the above error and what I need to do to resolve it?  Thanks in advance. /////////////////////////////// default.aspx  <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="XMLwalkthroughVB._default" %&...

Bind Data to an Image Control not in a Data Presentation Control
I've been searching for two days but I don't really know what to search for.I'm making a site for a photographer.  The Default.aspx page displays Albums by showing a title, image and description from the database table Albums. Click an album to view the contents and it passes the QueryString which is AlbumName.  The ViewAlbum.aspx page uses the QueryString to display an UpdatePanel holding a Large Image and a Repeater full of dynamically filled ImageButtons for thumbs.  Both are from the database table Photos and are retrieved using an ObjectDataSource. Click the ...

How to hide a Column Header in a Gridview?
I know how to make the data not visible - but the column header shows up even if there is no data in the column to display.  I have  ctype(gdv_disb_srch.Rows(i).FindControl("ddlCntyLoca"), DropDownList).Visible = False If certain criteria is not met, but this only makes the contents of the Cell not visible - how do I make the Column Header not visible as well? Thanks in advance for any help on this (you would think with all the work I have done with Gridviews lately I would know how to do this!...)    Coleen"We Develop Webs" If you'...

Showing the column headers of a GridView when there is no data
Hi, Is there a way to show the column headers of a GridView control even if there is no data? The only thing I see is the EmptyDataTemplate but I would also like to display the column headers. Thanks Hans...

Gridview
How to hide column by header name?Rafal Zikbay.com - Free Classifieds (Search Over 5 mln jobs on Zikbay.com) DNN Direct Hi There, Im not sure is there a better way to do thi, however this im sure is working. By looping thru GridView column, compare columnname with given comparer, set visible to false if found e.g.for ( int i = 0; i < GridView1.Columns.Count; i ++ ) {if (GridView1.Columns[i].ColumnName.ToLower().Equals("ColumnName")) {GridView1.Columns[i].Visible = false;break; } }DC517Don't forget to click "Mark as Answer" on the post that helped you. ...

Freeze Column Headers in gridview controls?
Is there a way to freeze the column header row in a gridview control?I am displaying a large table, so the users have to scroll sideways and up and down. I tried to improve this by putting the gridview in a panel, so they can scroll using the panel's scroll buttons and I am able to specify the size of the display. However, if the users scroll down, they loose the name of the columns. Orlando. Here is a way: http://web.tampabay.rr.com/bmerkey/examples/locked-column-csv.htmlSteve Wellens My blog Thank you for that information. It's what I need, but I need to apply this to a gridview, ...

Display only Columns that have Data in GridView Control
Good evening to the community, thanks for the help that ever provideThe situation is the following:I'm working in a application that have like 50 columns in the Database that represents Earning Codes for employees, but most of the times only 10 are used.What if something can be done to only display in the GridView Control the columns that the value is different than Null. Thanks for any lead evick   If you set the gridview to auto create the columns based on the datasource then when selecting data from the db only return the columns that have data in them. aspro Please m...

Web resources about - Hide Gridview Column (incl Header) if contains no data - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 1/23/2016 6:30:06 PM