Gộp cột tiêu đề (Merger header columns) trong Gridview
(How to Merge Header Columns in GridView) – Chức năng Merge Cell đã quá quen thuộc trong Excel, nó giúp người sử dụng gộp 2 hay nhiều ô thành 1. Vậy chức năng Merge Cell có trong Gridview không? Hiện Gridview có hỗ trợ chức năng Merge Header Columns, tuy nhiên để sử dụng nó người lập trình phải xử lý bằng Code. Dưới đây là cách để Merge Header Columns Gridview.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- B2: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace MergeHeaderColumnsinGridView
{
public class SqlDataProvider
{
#region "Membres Prives"
private string _connectionString;
#endregion
#region "Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region "Proprietes"
public string ConnectionString
{
get { return _connectionString; }
}
#endregion
#region "Functions"
public DataTable FillTable(string sql)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(string Pname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public object Value
{
get { return _Value; }
set { _Value = value; }
}
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace MergeHeaderColumnsinGridView
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString As String
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() As String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function FillTable(ByVal sql As String) As DataTable
Try
Dim tb As New DataTable
Dim adap As New SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
Public Class ObjectPara
Dim _name As String
Dim _Value As Object
Sub New(ByVal Pname As String, ByVal PValue As Object)
_name = Pname
_Value = PValue
End Sub
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Value() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B3: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page
Title="How to
Merge Header Columns in GridView" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MergeHeaderColumnsinGridView._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
How
to Merge Header Columns in GridView
</h3>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<tr
id="trMessage"
runat="server"
visible="false">
<td
colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td
colspan="2">
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
DataKeyNames="EmployeeID"
width="100%"
OnRowCreated="grvObject_RowCreated"
OnRowDataBound="grvObject_RowDataBound"
OnPageIndexChanging="grvObject_PageIndexChanging">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="LastName">
<ItemStyle width="7%" />
<ItemTemplate>
<asp:Label ID="lblLastName"
Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemStyle width="7%" />
<ItemTemplate>
<asp:Label ID="lblFirstName"
Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblTitle"
Text='<%# Eval("Title") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Street">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblStreet"
Text='<%# Eval("Address") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemStyle width="8%" />
<ItemTemplate>
<asp:Label ID="lblCity"
Text='<%# Eval("City") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PostalCode">
<ItemStyle width="8%" />
<ItemTemplate>
<asp:Label ID="lblPostalCode"
Text='<%# Eval("PostalCode") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Region">
<ItemStyle width="5%" />
<ItemTemplate>
<asp:Label ID="lblRegion"
Text='<%# Eval("Region") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HomePhone">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblHomePhone"
Text='<%# Eval("HomePhone") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>VB.Net Code
<%@ Page
Title="How to
Merge Header Columns in GridView" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="MergeHeaderColumnsinGridView._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
How
to Merge Header Columns in GridView
</h3>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<tr
id="trMessage"
runat="server"
visible="false">
<td
colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td
colspan="2">
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="EmployeeID" width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="LastName">
<ItemStyle width="7%" />
<ItemTemplate>
<asp:Label ID="lblLastName"
Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemStyle width="7%" />
<ItemTemplate>
<asp:Label ID="lblFirstName"
Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblTitle"
Text='<%# Eval("Title") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Street">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblStreet"
Text='<%# Eval("Address") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemStyle width="8%" />
<ItemTemplate>
<asp:Label ID="lblCity"
Text='<%# Eval("City") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PostalCode">
<ItemStyle width="8%" />
<ItemTemplate>
<asp:Label ID="lblPostalCode"
Text='<%# Eval("PostalCode") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Region">
<ItemStyle width="5%" />
<ItemTemplate>
<asp:Label ID="lblRegion"
Text='<%# Eval("Region") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HomePhone">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblHomePhone"
Text='<%# Eval("HomePhone") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B4: Viết Code cho file Default.aspx
C#
//Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MergeHeaderColumnsinGridView
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Bind Data"
private void
BindEmployees()
{
DataTable objBind = new
DataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
grvObject.DataSource = objBind;
grvObject.DataBind();
trMessage.Visible = false;
grvObject.Visible = true;
updatePanel.Update();
}
else
{
trMessage.Visible = true;
grvObject.Visible = false;
}
}
}
private DataTable
BindData()
{
SqlDataProvider objSQL = new
SqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Employees.* From Employees");
return objBind;
}
#endregion
#region
"GridView Methods"
protected void
grvObject_RowCreated(object sender,
System.Web.UI.WebControls.GridViewRowEventArgs
e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderRow = new GridViewRow(0,
0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell Cell_Header = new TableCell();
Cell_Header.Text = "Contact";
Cell_Header.HorizontalAlign = HorizontalAlign.Center;
Cell_Header.ColumnSpan = 3;
HeaderRow.Cells.Add(Cell_Header);
Cell_Header = new TableCell();
Cell_Header.Text = "Address";
Cell_Header.HorizontalAlign = HorizontalAlign.Center;
Cell_Header.ColumnSpan = 4;
HeaderRow.Cells.Add(Cell_Header);
Cell_Header = new TableCell();
Cell_Header.Text = "HomePhone";
Cell_Header.HorizontalAlign = HorizontalAlign.Center;
Cell_Header.ColumnSpan = 1;
Cell_Header.RowSpan = 2;
HeaderRow.Cells.Add(Cell_Header);
grvObject.Controls[0].Controls.AddAt(0, HeaderRow);
}
}
protected void
grvObject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[7].Visible = false;
}
}
protected void
grvObject_PageIndexChanging(object sender,
System.Web.UI.WebControls.GridViewPageEventArgs
e)
{
grvObject.PageIndex = e.NewPageIndex;
BindEmployees();
}
#endregion
#region
"Event Handles"
protected void
Page_Load(object sender, System.EventArgs e)
{
try
{
if
(!IsPostBack)
{
BindEmployees();
}
}
catch
{
}
}
#endregion
}
}
VB.NET Code
Namespace MergeHeaderColumnsinGridView
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private Sub BindEmployees()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
updatePanel.Update()
Else
trMessage.Visible = True
grvObject.Visible = False
End If
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Select Employees.* From Employees")
Return objBind
End Function
#End Region
#Region "GridView
Methods"
Private Sub
grvObject_RowCreated(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewRowEventArgs)
Handles grvObject.RowCreated
If e.Row.RowType = DataControlRowType.Header
Then
Dim HeaderGrid As
GridView = DirectCast(sender,
GridView)
Dim HeaderRow As
New GridViewRow(0,
0, DataControlRowType.Header, DataControlRowState.Insert)
Dim Cell_Header As
New TableCell()
Cell_Header.Text = "Contact"
Cell_Header.HorizontalAlign = HorizontalAlign.Center
Cell_Header.ColumnSpan = 3
HeaderRow.Cells.Add(Cell_Header)
Cell_Header = New TableCell()
Cell_Header.Text = "Address"
Cell_Header.HorizontalAlign = HorizontalAlign.Center
Cell_Header.ColumnSpan = 4
HeaderRow.Cells.Add(Cell_Header)
Cell_Header = New TableCell()
Cell_Header.Text = "HomePhone"
Cell_Header.HorizontalAlign = HorizontalAlign.Center
Cell_Header.ColumnSpan = 1
Cell_Header.RowSpan = 2
HeaderRow.Cells.Add(Cell_Header)
grvObject.Controls(0).Controls.AddAt(0, HeaderRow)
End If
End Sub
Private Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles
grvObject.RowDataBound
If e.Row.RowType = DataControlRowType.Header
Then
e.Row.Cells(7).Visible = False
End If
End Sub
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindEmployees()
End Sub
#End Region
#Region "Event
Handles"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
If Page.IsPostBack = False Then
BindEmployees()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
No Comment to " Gộp cột tiêu đề (Merger header columns) trong Gridview "