Sunday, 27 October 2013

Group Columns in Asp.net Gridview Header Row & Display Multiple Columns Under Single Column

Introduction:

Here I will explain how to group columns in asp.net gridview header row in C#.

To group columns in gridview we need to write the code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Group Gridview Columns in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server"
OnRowDataBound="gvDetails_RowDataBound">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
Now in code behind add the following namespaces

C# Code


using System;
using System.Data;
using System.Web.UI.WebControls;
After that add below code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId"typeof(Int32));
dt.Columns.Add("UserName"typeof(string));
dt.Columns.Add("Education"typeof(string));
dt.Columns.Add("Location"typeof(string));
dt.Rows.Add(1, "Vamsi""MCA""Chennai");
dt.Rows.Add(2, "Balu""MCA""Bangalore");
dt.Rows.Add(3, "Lasya""MCA""Bangalore");
dt.Rows.Add(4, "Swetha""MCA""Bangalore");
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvRow = e.Row;
if (gvRow.RowType == DataControlRowType.Header)
{
GridViewRow gvrow = new GridViewRow(0, 0, DataControlRowType.Header
DataControlRowState.Insert);
TableCell cell0 = new TableCell();
cell0.Text = "Age Group";
cell0.HorizontalAlign = HorizontalAlign.Center;
cell0.ColumnSpan = 2;
TableCell cell1 = new TableCell();
cell1.Text = "No. Of Employees";
cell1.HorizontalAlign = HorizontalAlign.Center;
cell1.ColumnSpan = 2;
gvrow.Cells.Add(cell0);
gvrow.Cells.Add(cell1);
gvDetails.Controls[0].Controls.AddAt(0, gvrow);
}
}

Demo

1 comment:

  1. Hi
    I if i use this Group Columns in Asp.net Gridview Header Row & Display Multiple Columns Under Single Column

    and if i try to save that data into database to not save last row data what is the solution for t
    his

    please reply it's urgent

    ReplyDelete

Receive All Free Updates Via Facebook.