locked
How can I add Caption/Title to GridView? RRS feed

  • Question

  • User153155060 posted

    Have you ever wanted to add a Title or Caption to your GridView (i.e. at the top of your GridView control)?  Some of you may already be aware of the GridView.Caption property, but entering your caption text displays a simple text rather than being able to define styles like other GridView elements.  Well, I think there is a way to get around this limitation.

    While trying to answer one of the post about GridView.Caption property, I realized that you can assign a full HTML rather than a simple text.  This means that you can be creative in designing what your caption looks like.  Following simple example illustrates using some HTML tags to define the border and background color to the caption area:

    <asp:GridView ID="GridView1" runat="server" ...

    Caption='<table border="1" width="100%" cellpadding="0" cellspacing="0" bgcolor="yellow"><tr><td>Grid Heading</td></tr></table>'

    CaptionAlign="Top">

    What this does is to insert a Table that fills the Caption region (width="100%" ensures same width as that of the GridView) while using Yellow background color.  What's more, it opens the door to adding captions that are limited only by your imagination.  Happy coding.

    Friday, February 24, 2006 1:26 PM

All replies

  • User-904968987 posted

    this is a very nice thing. thanks

    also made me realize i had a blue background set, even though i'm using a background image, since i applied bgcolor=transperant on the caption :)

    Sunday, April 2, 2006 5:49 PM
  • User-1724703109 posted

    Tht's great...
    I'm using it, but instead of formatting the attributtes directly I'm using an CssStyle and works wonderful...

    Thanks,

    Thursday, September 21, 2006 10:27 AM
  • User-1366313035 posted
    how can we add caption using CssStyle?
    Wednesday, October 4, 2006 11:50 PM
  • User-1724703109 posted

    For example, creating the table inside the caption as sugestted by JCasp, but instead of defining the background color, image or the table borders in each time you set a title for your grid, the class attibute can be set in the HTML code as in the code below :

    <asp:GridView ID="GridView1" runat="server" ... caption='<table width="100%" class="TestCssStyle"><tr><td class="text_Title">Grid Heading</td></tr></table>'>

     

    And in the CSS file, the TestCssStyle could be whatever you  want:

    .testCssStyle
    {
    color: #1f5ca9;
    background-color: #c5d4e6;
    table-layout: auto;
    border-collapse: separate;
    border-right: gray thin solid;
    border-top: gray thin solid;
    border-left: gray thin solid;
    border-bottom: gray thin solid;
    }

     Hope it helps.... 

    Thursday, October 5, 2006 4:52 AM
  • User-1145630377 posted

    I found a slightly better way to do just that using CSS

    Instead of adding code in the Caption, leave the Caption to be Caption="My Title".

    Then, if the gridview CssClass is "gv" than by setting the ".gv caption" in your stylesheet you can manipulate the caption as you wish.

     .gv caption
    {
    text-align:left;
    font-weight:bold;
    font-size:larger;
    padding: 2px;
    background-color: Red;
    }

    Note that you still need to use the CaptionAlign="WHATEVER" to tell the browser where to place the caption in relation to the gridview.

    Zozo

     

    Sunday, May 27, 2007 6:14 AM
  • User-246671484 posted

    I thought I'd share my solution, it's just an alternative approach to the same problem. In my solution, I created a custom control that inherits from the GridView. I just added a Caption Template to the original control. You can edit the Caption template for your gridview from the Visual Studio designer instead of having to switch to source view to add a formatted HTML caption manually. Another nice thing about this is that you can simply drag in other controls into your Caption template just as if it were any other gridview row template.

    Here's the source code:

    Imports Microsoft.VisualBasic
    Imports System
    Imports System.ComponentModel
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.Design
    
    Namespace YourCompanyName.WebControls
    
        <Designer(GetType(CaptionTemplateDesigner))> _
        <ToolboxData("<{0}:GridViewWithCaption runat=server></{0}:GridViewWithCaption>")> _
        <ParseChildren(True)> _
        Public Class GridViewWithCaption
            Inherits System.Web.UI.WebControls.GridView
    
            Private _captionTemplate As ITemplate
            Private _totalColumns As Integer
    
            Public Sub New()
            End Sub
    
            <Browsable(False)> _
            <PersistenceMode(PersistenceMode.InnerProperty)> _
            <TemplateContainer(GetType(CaptionContainer))> _
            Public Property CaptionTemplate() As ITemplate
                Get
                    Return _captionTemplate
                End Get
                Set(ByVal value As ITemplate)
                    _captionTemplate = value
                End Set
            End Property
    
            Protected Overloads Overrides Sub PrepareControlHierarchy()
                MyBase.PrepareControlHierarchy()
                Dim t As Table = CType(Controls(0), Table)
                If Not (_captionTemplate Is Nothing) AndAlso String.IsNullOrEmpty(Caption) Then
                    Dim row As TableRow = New TableRow
                    t.Rows.AddAt(0, row)
                    Dim cell As TableCell = New TableCell
                    cell.ColumnSpan = _totalColumns
                    row.Cells.Add(cell)
                    Dim cc As CaptionContainer = New CaptionContainer(Me)
                    _captionTemplate.InstantiateIn(cc)
                    cell.Controls.Add(cc)
                    cell.DataBind()
                End If
                Return
            End Sub
    
            Protected Overloads Overrides Function CreateColumns(ByVal dataSource As PagedDataSource, ByVal useDataSource As Boolean) As ICollection
                Dim coll As ICollection = MyBase.CreateColumns(dataSource, useDataSource)
                _totalColumns = coll.Count
                Return coll
            End Function
        End Class
    
        Public Class CaptionContainer
            Inherits WebControl
            Implements INamingContainer
            Private _grid As GridViewWithCaption
    
            Public Sub New(ByVal g As GridViewWithCaption)
                _grid = g
            End Sub
    
            Public ReadOnly Property GridViewWithCaption() As GridViewWithCaption
                Get
                    Return _grid
                End Get
            End Property
    
        End Class
    
        ' Designer for the TemplateGroupsSample class
        Public Class CaptionTemplateDesigner
            Inherits System.Web.UI.Design.WebControls.GridViewDesigner
            'Inherits System.Web.UI.Design.ControlDesigner
    
            Private o_TemplateGroups As TemplateGroupCollection = Nothing
    
            Public Overrides Sub Initialize(ByVal Component As IComponent)
                ' Initialize the base
                MyBase.Initialize(Component)
                ' Turn on template editing
                SetViewFlags(ViewFlags.TemplateEditing, True)
            End Sub
    
            Public Overrides ReadOnly Property TemplateGroups() As TemplateGroupCollection
                Get
    
                    If IsNothing(o_TemplateGroups) Then
                        o_TemplateGroups = MyBase.TemplateGroups
    
                        Dim o_TemplateGroup As TemplateGroup
                        Dim o_TemplateDefinition As TemplateDefinition
                        Dim ctl As GridViewWithCaption = CType(Component, GridViewWithCaption)
    
                        o_TemplateGroup = New TemplateGroup("Caption Template")
                        o_TemplateDefinition = New TemplateDefinition(Me, "Caption Template", ctl, "CaptionTemplate", False)
                        o_TemplateGroup.AddTemplateDefinition(o_TemplateDefinition)
                        o_TemplateGroups.Add(o_TemplateGroup)
    
                    End If
    
                    Return o_TemplateGroups
    
                End Get
    
            End Property
    
        End Class
    
    
    End Namespace
     
    Sunday, May 27, 2007 1:11 PM
  • User1519061510 posted

    you can use headerstyle tag to add style to gridview caption.check it !

     

    Tuesday, May 29, 2007 1:09 AM
  • User-1145630377 posted

    you can use headerstyle tag to add style to gridview caption.check it !

    I belive the headerstyle tag referes to the coulmn headers of the grid coulmns and NOT to the Caption.

    Zozo

    Tuesday, May 29, 2007 2:16 PM
  • User1656302604 posted

    Thank you soo much.  I used this method with an H4 tag instead of a table and it rocked!  It also carried over the H4 CSS style from the stylesheet.

     Great tip.

     

    Wednesday, February 27, 2008 3:58 PM
  • User-935636848 posted

     

    <asp:GridView ID="GridView1" runat="server" ...

     

     Caption='<table border="1" width="100%" cellpadding="0" cellspacing="0" bgcolor="yellow"><tr><td>Grid Heading</td></tr></table>'

    CaptionAlign="Top">


    i am using following code..

          <asp:GridView ID="grdattendncereport" runat="server"
                    BorderWidth="3px" CellPadding="4"
                     CssClass="GridViewStyle" HeaderStyle-BackColor="#346BAF"
                     HeaderStyle-ForeColor="white" HorizontalAlign="Center"
                     onrowcreated="grdattendncereport_RowCreated" RowStyle-                     HorizontalAlign="Center"
                     Caption='<table width="100%"><tr>
                     <td colspan="3"  align="center">
                      <asp:Label ID="lblshift" runat="server" Text=""></asp:Label></td>
               <tr><td colspan="3">
                 <asp:Label ID="lblterm" runat="server" Text=""></asp:Label></td>
               </tr>
             
    </table>' CaptionAlign="Top" > ...

    and i want to show some text in these titles in page load using following code.. 

              

    (Label)grdattendncereport.FindControl("lblshift").Text = shift;
    ((Label)grdattendncereport.FindControl(" lblterm")).Text = duration;


    but this is showing  nullreference Error....
    pls suggest me the proper way to show text in the title in Page load....

    ............................................................................thanks in advance..............







    Sunday, December 12, 2010 2:58 AM
  • User1556928295 posted

    I'm using the same code:

    Caption='<table width="100%"><tr><td colspan="3" align="center"><asp:Label ID="lblshift" runat="server" Text="Hello"></asp:Label></td></tr><tr><td colspan="3"><asp:Label ID="lblterm" runat="server" Text="Goodbye"></asp:Label></td></tr></table>'
    CaptionAlign="Top"> 

    But it won't display the heading. If I just put Text in the table it displays the text, but not if I put an object in the table like labels or textboxs.

    Thursday, May 14, 2015 2:31 PM
  • User-421675661 posted

    Thanks, it really helps me a lot.

    Thursday, August 4, 2016 9:04 AM