Hi akhter,
Please refer below sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false"
OnDataBound="gvDetails_DataBound">
<Columns>
<asp:BoundField HeaderText="CompanyName" DataField="ContactName" />
<asp:BoundField HeaderText="ContactName" DataField="ContactName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="City" DataField="City" />
</Columns>
</asp:GridView>
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GridViewBind();
}
}
private void GridViewBind()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Top 10 CompanyName, ContactName, Address, City FROM Customers", con))
{
con.Open();
gvDetails.DataSource = cmd.ExecuteReader();
gvDetails.DataBind();
con.Close();
}
}
}
protected void gvDetails_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "Name";
cell.ColumnSpan = 2;
row.Controls.Add(cell);
cell = new TableHeaderCell();
cell.ColumnSpan = 2;
cell.Text = "Address";
row.Controls.Add(cell);
gvDetails.HeaderRow.Parent.Controls.AddAt(0, row);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.GridViewBind()
End If
End Sub
Private Sub GridViewBind()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand("SELECT Top 10 CompanyName, ContactName, Address, City FROM Customers", con)
con.Open()
gvDetails.DataSource = cmd.ExecuteReader()
gvDetails.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub gvDetails_DataBound(ByVal sender As Object, ByVal e As EventArgs)
Dim row As GridViewRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal)
Dim cell As TableHeaderCell = New TableHeaderCell()
cell.Text = "Name"
cell.ColumnSpan = 2
row.Controls.Add(cell)
cell = New TableHeaderCell()
cell.ColumnSpan = 2
cell.Text = "Address"
row.Controls.Add(cell)
gvDetails.HeaderRow.Parent.Controls.AddAt(0, row)
End Sub
Screenshot
Reference: GridView with Multiple Headers in ASP.Net