2

I have to make the gridview using C# and ASP.NET. The gridview shown below get data from this SQL Server 2019 table dbfiddle

enter image description here

I have searched numerous times both on google and in Stackoverflow threads and I have written code; however, I cannot customize as per the attached screenshot.

I tried my code without success because this is the output from gridview (please do not look at the numbers in this table, because the data has been updated since the initial image... thanks):

enter image description here

How do I resolve this?

This is my code:

protected void OnDataBound(object sender, EventArgs e)
{
    GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);

    TableHeaderCell cell = new TableHeaderCell();

    cell = new TableHeaderCell();
    cell.ColumnSpan = 1;
    cell.Text = "Hour";
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.ColumnSpan = 1;
    cell.Text = "C_CO";
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.Text = "710";
    cell.ColumnSpan = 3;
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.Text = "810";
    cell.ColumnSpan = 3;
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.ColumnSpan = 3;
    cell.Text = "830";
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.ColumnSpan = 3;
    cell.Text = "E10";
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.ColumnSpan = 3;
    cell.Text = "E40";
    row.Controls.Add(cell);

    cell = new TableHeaderCell();
    cell.ColumnSpan = 3;
    cell.Text = "TOTAL";
    row.Controls.Add(cell);

    row.BackColor = ColorTranslator.FromHtml("#3AC0F2");
    GridView1.HeaderRow.Parent.Controls.AddAt(0, row);
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    GridView1.DataSource = RetrieveProducts();
    GridView1.DataBind();
}

private DataTable RetrieveProducts()
{
    DataTable dt = new DataTable();
    DataSet ds = new DataSet();

    using (SqlConnection myConnectionString =
      new SqlConnection(ConfigurationManager.ConnectionStrings["ConnSqlServer"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("sp_C_CO", myConnectionString))
        {
            cmd.CommandTimeout = 2147483;
            cmd.Connection.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            adapter.Fill(ds);

            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
        }
    }

    return dt;
}


<asp:GridView ID="GridView1" HeaderStyle-BackColor="#9AD6ED" HeaderStyle-ForeColor="#636363"
              runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound">
    <Columns>
        <asp:BoundField DataField="xHour" HeaderText="" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150" HtmlEncode="false" />
        <asp:BoundField DataField="xDate" HeaderText="DateHour" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150" />
        <asp:BoundField DataField="Total" HeaderText="Total" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150" HtmlEncode="false" />
        <asp:BoundField DataField="A_RG" HeaderText="A_RG" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150" HtmlEncode="false" />
        <asp:BoundField DataField="B_RG" HeaderText="B_RG" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150" HtmlEncode="false" />
        <asp:BoundField DataField="c_RG" HeaderText="C_RG" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150" HtmlEncode="false" />
    </Columns>
</asp:GridView>
5
  • As per the question guide, please do not post images of code, data, error messages, etc. - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text. Commented Jun 1 at 8:26
  • I've removed the sql server tag, you don't need sql skills to resolve your issue. Commented Jun 1 at 8:28
  • @the_uncle_vince you can define template fields inside Columns and you can use whatever control you want, including further grid views. Here's an earlier question related to this stackoverflow.com/questions/62285354/… . Is this helpful for you? Commented Jun 1 at 9:38
  • @LajosArpad thanks, it's one of the threads I read but it didn't help me, feel sorry Commented Jun 1 at 9:51
  • @the_uncle_vince can you explain how you tried to apply it in your setup and what problem did you encounter as a result? Commented Jun 1 at 10:39

1 Answer 1

1

You are on the right track by using the OnRowDataBound to add an extra row. Here is how can do what you want

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //cast the sender back to a gridview
    var gv = sender as GridView;

    //the list of header names for the extra row
    var HeaderNames = new List<string>()
            {
                "710",
                "810",
                "830",
                "E10",
                "E40",
                "TOTAL"
            };

    //check if the row is the header row
    if (e.Row.RowType == DataControlRowType.Header)
    {
        //create the first row
        var ExtraHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

        //add the first cell
        ExtraHeader.Cells.Add(new TableHeaderCell()
        {
            Text = "C-CO",
            CssClass = "header-lightorange"
        });

        //loop all the columns and create a new cell for each group of 3
        for (int i = 0; i < gv.Columns.Count / 3; i++)
        {
            ExtraHeader.Cells.Add(new TableHeaderCell()
            {
                Text = HeaderNames[i],
                CssClass = "header-lightorange",
                ColumnSpan = 3
            });
        }

        //add the new row to the gridview
        gv.Controls[0].Controls.AddAt(0, ExtraHeader);
    }
}

The ASPX

Note that the example GridView is strongly typed by using a class reference (MyNameSpace.Classes.Book) so you can use the properties of that class in the markup.

    <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false" 
        ItemType="MyNameSpace.Classes.Book" DataKeyNames="id" CssClass="table table-striped table-bordered border-secondary double-header-table">
        <Columns>
            <asp:TemplateField HeaderText="DataHour" HeaderStyle-CssClass="header-lightorange">
                <ItemTemplate>
                    <%# Item.Date %>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="total">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="A_RG">
                <ItemTemplate>
                    <%# Item.Category %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B_RG">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="total">
                <ItemTemplate>
                    <%# Item.Name %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="A_RG">
                <ItemTemplate>
                    <%# Item.Category %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B_RG">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="total">
                <ItemTemplate>
                    <%# Item.Name %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="A_RG">
                <ItemTemplate>
                    <%# Item.Category %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B_RG">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="total">
                <ItemTemplate>
                    <%# Item.Name %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="A_RG">
                <ItemTemplate>
                    <%# Item.Category %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B_RG">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="total">
                <ItemTemplate>
                    <%# Item.Name %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="A_RG">
                <ItemTemplate>
                    <%# Item.Category %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B_RG">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="total" HeaderStyle-CssClass="header-green">
                <ItemTemplate>
                    <%# Item.Name %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="A_RG" HeaderStyle-CssClass="header-green">
                <ItemTemplate>
                    <%# Item.Category %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="B_RG" HeaderStyle-CssClass="header-green">
                <ItemTemplate>
                    <%# Item.ID %>
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>

    <style>
        .double-header-table th {
            background-color: #e9ab84
        }

        .double-header-table .header-lightorange {
            background-color: #f8e3d5;
        }

        .double-header-table .header-green {
            background-color: #88e68d
        }
    </style>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I don't understand this MyNameSpace.Classes.Book ? where is it?
It's just an example to make a GridView strongly typed. But you can remove ItemType="MyNameSpace.Classes.Book" and DataKeyNames="id" and just use the GridView normally like you are used to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.