Tuesday, November 6, 2012

How to create multiple row header and merge it with other columns in GridView

In sometime showing single header is not enough in our application and we might require showing more than one header to categorize the columns. This blog concentrates on how to design the ASP.NET GridView control to have more than one row header.

Before going for implementation let us understand the actual requirement we are going to implement in this post,

I have an XML file in my project which has five columns. The screen short of the records are:
Excel sheet screen shot of the data

The XML file looks like this:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8" ?>
<RevenueReport>
   
  <Data Year="2008" Period="Q1" AuditedBy="Maria Anders" DirectRevenue="12500.00" ReferralRevenue="2500.00" />
  <Data Year="2008" Period="Q2" AuditedBy="Ana Trujillo" DirectRevenue="21000.00" ReferralRevenue="8000.00" />
  <Data Year="2008" Period="Q3" AuditedBy="Antonio Moreno" DirectRevenue="20000.00" ReferralRevenue="5000.00" />
  <Data Year="2008" Period="Q4" AuditedBy="Thomas Hardy" DirectRevenue="25000.00" ReferralRevenue="1200.00" />
  <Data Year="2009" Period="Q1" AuditedBy="Christina Berglund" DirectRevenue="72500.00" ReferralRevenue="5000.00" />
  <Data Year="2009" Period="Q2" AuditedBy="Hanna Moos" DirectRevenue="15000.00" ReferralRevenue="6500.00" />
  <Data Year="2009" Period="Q3" AuditedBy="Thomas Hardy" DirectRevenue="25000.00" ReferralRevenue="1520.00" />
  <Data Year="2009" Period="Q4" AuditedBy="Martín Sommer" DirectRevenue="42000.00" ReferralRevenue="2580.00" />
  <Data Year="2010" Period="Q1" AuditedBy="Laurence Lebihan" DirectRevenue="12500.00" ReferralRevenue="1500.00" />
  <Data Year="2010" Period="Q2" AuditedBy="Elizabeth Lincoln" DirectRevenue="25000.00" ReferralRevenue="5500.00" />
  <Data Year="2010" Period="Q3" AuditedBy="Hanna Moos" DirectRevenue="12000.00" ReferralRevenue="1800.00" />
  <Data Year="2010" Period="Q4" AuditedBy="Antonio Moreno" DirectRevenue="10000.00" ReferralRevenue="1200.00" />
   
</RevenueReport>

I required of Grid View is

Required output of the GridView

To implement this requirement, we have to follow the same concept we normally implement for html table with colspan and rowspan attributes.

The following points explains the same:

  1. Initially when we bind the records to GridView, the page will be like the following image. (Here the DirectReferralTotal heading has bound using XML file column name, we have to change the heading to what explained before)

    Normal GridView output (bind from XML file)
  2. For .NET runtime, header is also a row. So once the header row created, we have to manually add one more row above the header which has been created by .NET runtime and add required columns by merging with other columns. To do this we have to use the RowCreated event on GridView. The output will be as follows:

    After adding one more row on top of the actual header and merging the columns
    Here the first row created and added by our program code.
  3. Here, the first three columns are required to be merged with row (means first row Year, second row Year cells required to be merged). But the second row Year cell already created by normal binding method (using .NET runtime). So to achieve this, we required to Invisible (hide) the second row Year cell. The same will applied for Period and Audited By columns.

    To do this we can use RowDataBound event of GridView. The final output is below.

    After merging first three columns with its next row

The implementation is follows: 

GridView Script

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<asp:GridView ID="grdViewProducts" runat="server" AutoGenerateColumns="False" TabIndex="1"
    Width="100%" DataSourceID="XmlDataSource1" ShowFooter="false"
    CellPadding="4" ForeColor="Black" GridLines="Vertical"
    BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
    OnRowDataBound="grdViewProducts_RowDataBound"
    onrowcreated="grdViewProducts_RowCreated" >
    <RowStyle BackColor="#F7F7DE" />
    <Columns>
        <asp:BoundField DataField="Year" HeaderText="Year" ItemStyle-HorizontalAlign="Left" >
        </asp:BoundField>
        <asp:BoundField DataField="Period" HeaderText="Period" ItemStyle-HorizontalAlign="Left" >
        </asp:BoundField>
        <asp:BoundField DataField="AuditedBy" HeaderText="Audited By" ItemStyle-HorizontalAlign="Left" >
        </asp:BoundField>
        <asp:BoundField DataField="DirectRevenue" HeaderText="Direct" ItemStyle-HorizontalAlign="Right" >
        </asp:BoundField>
        <asp:BoundField DataField="ReferralRevenue" HeaderText="Referral" ItemStyle-HorizontalAlign="Right" >
        </asp:BoundField>
        <asp:TemplateField HeaderText="Total">
            <ItemStyle HorizontalAlign="Right" />
            <ItemTemplate>
                <asp:Label runat="server" ID="lblTotalRevenue" Text="0" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
     
    <FooterStyle BackColor="#CCCC99" />
    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
    <HeaderStyle CssClass="HeaderStyle" />
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="Data/RevenueReport.xml"></asp:XmlDataSource>

Code behind Code

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
protected void grdViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // Invisibling the first three columns of second row header (normally created on binding)
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Visible = false; // Invisibiling Year Header Cell
        e.Row.Cells[1].Visible = false; // Invisibiling Period Header Cell
        e.Row.Cells[2].Visible = false; // Invisibiling Audited By Header Cell
    }
    // This is for calculation of last column (Total = Direct + Referral)
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        double dblDirectRevenue = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "DirectRevenue").ToString());
        double dblReferralRevenue = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "ReferralRevenue").ToString());
        Label lblTotalRevenue = ((Label)e.Row.FindControl("lblTotalRevenue"));
        lblTotalRevenue.Text = string.Format("{0:0.00}", (dblDirectRevenue + dblReferralRevenue));
    }
}
protected void grdViewProducts_RowCreated(object sender, GridViewRowEventArgs e)
{
    // Adding a column manually once the header created
    if (e.Row.RowType == DataControlRowType.Header) // If header created
    {
        GridView ProductGrid = (GridView)sender;
        // Creating a Row
        GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
        //Adding Year Column
        TableCell HeaderCell = new TableCell();
        HeaderCell.Text = "Year";
        HeaderCell.HorizontalAlign = HorizontalAlign.Center;
        HeaderCell.RowSpan = 2; // For merging first, second row cells to one
        HeaderCell.CssClass = "HeaderStyle";
        HeaderRow.Cells.Add(HeaderCell);
        //Adding Period Column
        HeaderCell = new TableCell();
        HeaderCell.Text = "Period";
        HeaderCell.HorizontalAlign = HorizontalAlign.Center;
        HeaderCell.RowSpan = 2;
        HeaderCell.CssClass = "HeaderStyle";
        HeaderRow.Cells.Add(HeaderCell);
        //Adding Audited By Column
        HeaderCell = new TableCell();
        HeaderCell.Text = "Audited By";
        HeaderCell.HorizontalAlign = HorizontalAlign.Center;
        HeaderCell.RowSpan = 2;
        HeaderCell.CssClass = "HeaderStyle";
        HeaderRow.Cells.Add(HeaderCell);
        //Adding Revenue Column
        HeaderCell = new TableCell();
        HeaderCell.Text = "Revenue";
        HeaderCell.HorizontalAlign = HorizontalAlign.Center;
        HeaderCell.ColumnSpan = 3; // For merging three columns (Direct, Referral, Total)
        HeaderCell.CssClass = "HeaderStyle";
        HeaderRow.Cells.Add(HeaderCell);
        //Adding the Row at the 0th position (first row) in the Grid
        ProductGrid.Controls[0].Controls.AddAt(0, HeaderRow);
    }
}

Style Sheet

?
1
2
3
4
5
6
.HeaderStyle{
    border:solid 1px White;
    background-color:#81BEF7;
    font-weight:bold;
    text-align:center;
}

Here are the outputs of our example:

Output of Adding two row header and merging with adjacent cells

No comments:

Post a Comment