Click here to Skip to main content
Click here to Skip to main content

Add an extra header to an ASP.NET DataGrid

By , 9 Dec 2005
 

Sample Image - grid.jpg

Introduction

This article explains how to add an extra header item to a standard ASP.NET DataGrid.

Using the code

The code is pretty simple. The grid is built using a DataGridTable object. All we have to do is to add a DataGridItem to the Rows collection in the CreateControlHierarchy method of our custom grid. Now I'll let the code talk:

Protected Overrides Sub CreateControlHierarchy(ByVal useDataSource As Boolean)
    MyBase.CreateControlHierarchy(useDataSource)
    If Not ShowExtraHeader Then Return
    If Controls.Count > 0 Then
        'get all grid's items (rows)
        Dim rows As TableRowCollection = DirectCast(Controls(0), Object).Rows
        'create extra header item
        Dim extraHeaderRow As DataGridItem = CreateItem(-1, -1, ListItemType.Header)
        'set an id that will identify it in ItemCreated event
        extraHeaderRow.ID = "extraheader"
        'create an event attached to our item
        Dim extraHeaderRowArgs As New DataGridItemEventArgs(extraHeaderRow)
        'call ItemCreated event
        OnItemCreated(extraHeaderRowArgs)
        'finally add the extra header item to the items's collection
        rows.AddAt(0, extraHeaderRow)
    End If
End Sub

And let's see how we could use this code in a real scenario:

Private Sub g_ItemCreated(ByVal sender As Object, ByVal e _
            As System.Web.UI.WebControls.DataGridItemEventArgs) Handles g.ItemCreated
    If e.Item.ItemType = ListItemType.Header Then
        If e.Item.ID = "extraheader" Then
            Dim refreshCell As New TableCell
            refreshCell.ColumnSpan = 2
            refreshCell.HorizontalAlign = HorizontalAlign.Center
            Dim btnRefresh As New Button
            btnRefresh.Text = "Refresh"
            refreshCell.Controls.Add(btnRefresh)
            AddHandler btnRefresh.Click, AddressOf btnRefresh_Click

            Dim parentsCell As New TableCell
            parentsCell.ColumnSpan = 2
            parentsCell.HorizontalAlign = HorizontalAlign.Center
            parentsCell.Text = "Parents"

            e.Item.Cells.Add(refreshCell)
            e.Item.Cells.Add(parentsCell)
        End If
    End If
End Sub

That's all! Check the demo project to see all the bits.

History

  • Dec. 10, 2005 - Version 1.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Gabriel Sirbu
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhow do i remove paging [modified]membermaya_zakry3 Jun '07 - 22:47 
hi.
i perform this method. i want to ask.. if u set the paging on, would it produce extra paging in the extra header. i have this problem..
does anybody have any idea on how do i remove the extra pager in the extraheader when the allow paging is set on.? urgent... this is my grid that has extraheader, with some buttons on it.. and the extra pager that i want to remove :-
http://picasaweb.google.com/maya.zakry/ScreenShots/photo#5050533591981982914[^]
 

-- modified at 4:52 Monday 4th June, 2007
GeneralItem_Databoud Eventmemberjhkss2 Nov '06 - 9:49 
I just added the code to the grid_itemdatabound event and it just worked. Thanks guys.
GeneralA Better Alternative.memberMiguel_TX29 Apr '06 - 18:40 
Check out this solution:
http://forums.asp.net/390809/ShowPost.aspx[^]
 
Here is the C# Equivalent (with some added stuff I did to help those with possible questions):
private void DataGrid1_PreRender(object sender, System.EventArgs e)
{
//This MUST be done in the Pre-Render function. Otherwise will have errors if running this code outside of the PreRender function.
DataGridItem dgItem = new DataGridItem(0,0,ListItemType.Header);
TableCell myCell = new TableCell();
myCell.ColumnSpan = 2; //This Merges Cells together.
myCell.Text = "Test";
myCell.BackColor = Color.Lavender; //Change the back color of a single cell.
myCell.VerticalAlign = VerticalAlign.Middle;//This Centers the text vertically for a single cell.
dgItem.Cells.Add(myCell);
dgItem.HorizontalAlign = HorizontalAlign.Center;//This centers the text for the entire dgItem (which in this case is the additional header we just added).
DataGrid1.Columns[1].HeaderStyle.BackColor = Color.LemonChiffon;//This changes the color for an entire column, not needed, but is neat to see if you were thinking about doing something like this in the future - now you know how to.
DataGrid1.Controls[0].Controls.AddAt(0, dgItem); //Change the integer in the AddAt() function to insert the header somewhere else in the datagrid (like 1 for below the original header, or 5 if for some inexplicable reason you want two totally separated headers with rows of data in between them.
}
 
Hope you guys liked it! Big Thanks to Jim Ross and his post at forums.ASP.Net website and his source who gave him the original VB code: Anand Hegde (MSFT).
- M

GeneralRe: A Better Alternative.memberGabriel Sirbu30 Apr '06 - 20:33 
I would say just "Another alternative" done in almost the same way,why is better? Mine is generic (if you haven't noticed),this one is "hard-coded" for one grid.
GeneralRe: A Better Alternative.memberJoel Pearson22 May '06 - 22:04 
This alternative doesn't work very well if you add delete buttons and the like.
 
When you click on Delete it deletes the row above, and if you click delete on the first row you get an exception. Basically because you add the extra row at the prerender stage it puts everything out. If you don't need to edit data, using prerender is quicker in the short term. But if you want your datagrid to work normally you need to do what this article suggests.
 
-Joel
GeneralRe: A Better Alternative.memberMiguel_TX12 Jun '06 - 20:32 
I'm sorry. You're right. I should have titled this "Another Alternative".
 
I'm not good when it comes to overriding functions. When I try I always get that feeling like when you're taking something apart that has seals and stickers on it warning you not to tamper with it. I had made my own custom-web-user-control and just dropped a datagrid in there and I added code to it as needed (like formatting and whatnot). Then when I need a datagrid on my site, I just plop my custom-web-user-control (the one with the tricked-out datagrid) and wire it up for data binding.
 
I don't use any editing controls created by the "Property Builder" with the datagrid - instead I add button columns by hand to do what I need. So yes this is "hard-coded for one grid", but it's a grid I use over and over again, so I only change or update the code in one place - the web-user-control I made for it. I just declare the DataGrid as public and I can do whatever I want to it from the page I dropped it in.
 
I hard-coded a button column and put a break-point in the DataGrid1_ItemCommand function and the row that I clicked on was the same index that appeared in this function and it pulled the same data that was binded to the grid for that row. I honestly hadn't tried it before until one of you mentioned your delete buttons were not functioning properly. Sorry about that too - I don't know what to say, other that it appears to work for me and that maybe - just maybe - the Property Builder's delete button doesn't work when using it this way. Did you use the "Property Builder" to add it?
 
I even changed the line of code I was using from DataGridItem(0,0,ListItemType.Header) to DataGridItem(-1,-1,ListItemType.Header) and they both appeared the same on the web page and clicking on my button column pulled the right data for both. I'm leaving it as DataGridItem(-1,-1,ListItemType.Header) - not that it makes any noticeable difference to me, I just think negatives are cool.
 
Well, enough about that I guess - we both appear to have something that works and thank you for trying it out and also for your gracious feedback. I do have some things for everyone to consider. Have you tried hiding columns? Wow - what a pain that was. I figured a workaround for it and thought I'd try the same with your solution and found that the posted solution has the same problem. Try adding this line to your code and see for yourself:
g.DataSource = GetSource()
g.Columns(1).Visible = False 'this hides the "age" column, and guess what else!
g.DataBind()
 
Yep, that middle line messes with your grid when you hide a column. It took me quite a while to figure it out and since you guys have been so helpful, I thought I'd pass this "Other Solution" on to my cyber-friends. The root of the problem is this, when you insert that DataGridItem what it is doing is taking the properties from the Column Header and applying them to the additional header you've added. Sure this is great at first because you keep the same formatting from your original header to the new one you've added, but if the column is hidden, that means the new header cell derived from that hidden column (with the same column index) will be hidden as well.
 
Confused yet? I'm sure you guys aren't, so I'll point this out for the rest (like me) that stumbled on this post. Even though you set a column span of 2 for the first cell of the new header, it doesn't mean it takes the properties of the first two cells of the original header - it is still only for the first cell of the second header.
 
Okay, enough yapping, here is the workaround:
Private Sub g_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles g.ItemCreated
If e.Item.ItemType = ListItemType.Header Then
If e.Item.ID = "extraheader" Then
 
Dim refreshCell As New TableCell
refreshCell.ColumnSpan = 1 'This used to be 2, but changed it to 1 since the "age" column below is hidden, so only one cell ("name") is left to cover.
refreshCell.HorizontalAlign = HorizontalAlign.Center
Dim btnRefresh As New Button
btnRefresh.Text = "Refresh"
refreshCell.Controls.Add(btnRefresh)
AddHandler btnRefresh.Click, AddressOf btnRefresh_Click
e.Item.Cells.Add(refreshCell)
 
Dim workaroundCell As New TableCell
workaroundCell.ColumnSpan = 20 'doesn't matter the column span, took me a while to wrap my head around this one, but I get it now and I hope others will too.
workaroundCell.HorizontalAlign = HorizontalAlign.Center
workaroundCell.Text = "You will never see me when 'age' column is hidden"
e.Item.Cells.Add(workaroundCell)
 
Dim parentsCell As New TableCell
parentsCell.ColumnSpan = 2
parentsCell.HorizontalAlign = HorizontalAlign.Center
parentsCell.Text = "Parents"
e.Item.Cells.Add(parentsCell)
 
End If
End If
End Sub
 
Ugly, isn't it? I worked out my code to dynamically add the "filler" cells to workaround hidden columns, so now I can keep reusing my code without worrying about it again. Good luck fixing this in your solution - though that is if you ever plan to hide any columns... ever.
 
- M
GeneralRe: A Better Alternative.memberdga20522 Jun '06 - 4:41 
I tried this code, and it works.
The problem is when I put, for example, a button, for each click that I do, a new blank row is inserted in the grid.
 
I can not find the problem
Generalc#memberMark Lawson29 Dec '05 - 9:39 
Hi,
 
Can you supply a C# version of this code please.
 
The line that uses Directcast is giving me the problem
 
Cheers
Mark
 
-- modified at 16:19 Thursday 29th December, 2005
GeneralRe: c#membersyao16825 Feb '06 - 10:07 
Try
 
TableRowCollection rows = ((Table) Controls[0]).Rows;
 
Steven
Generalc#memberMark Lawson29 Dec '05 - 9:38 
Hi,

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 9 Dec 2005
Article Copyright 2005 by Gabriel Sirbu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid