Click here to Skip to main content
15,889,116 members
Articles / Web Development / IIS

Add an extra header to an ASP.NET DataGrid

Rate me:
Please Sign up or sign in to vote.
3.22/5 (3 votes)
9 Dec 2005CPOL 58.4K   204   19   10
This article explains how to add an extra header item to a standard ASP.NET DataGrid.

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:

VB
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:

VB
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)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow do i remove paging [modified] Pin
maya_zakry3-Jun-07 22:47
maya_zakry3-Jun-07 22:47 
GeneralItem_Databoud Event Pin
jhkss2-Nov-06 9:49
jhkss2-Nov-06 9:49 
GeneralA Better Alternative. Pin
Miguel_TX29-Apr-06 18:40
Miguel_TX29-Apr-06 18:40 
GeneralRe: A Better Alternative. Pin
Gabriel Sirbu30-Apr-06 20:33
Gabriel Sirbu30-Apr-06 20:33 
GeneralRe: A Better Alternative. Pin
Joel Pearson22-May-06 22:04
Joel Pearson22-May-06 22:04 
GeneralRe: A Better Alternative. Pin
Miguel_TX12-Jun-06 20:32
Miguel_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. Pin
dga20522-Jun-06 4:41
dga20522-Jun-06 4:41 
Generalc# Pin
Mark Lawson29-Dec-05 9:39
Mark Lawson29-Dec-05 9:39 
GeneralRe: c# Pin
syao16825-Feb-06 10:07
syao16825-Feb-06 10:07 
Generalc# Pin
Mark Lawson29-Dec-05 9:38
Mark Lawson29-Dec-05 9:38 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.