News Ticker

Menu

Hiển thị tổng (Total) trong Footer của Gridview

(Hiển thị tổng giá trị một cột trong Footer của Gridview) – Đối với những dữ liệu số hiển thị trong 1 cột, nếu không có chức năng tổng phía dưới, người dùng khi cần xem thường phải mất thêm thao tác là Copy vào Excel rồi dùng hàm để tính. Như vậy rất bất tiện cho người dùng nếu có nhiều dòng và nhiều cột. Vậy làm sao để người dùng k phải Copy dữ liệu sang Excel mà vẫn có thể biết được tổng tổng giá trị các dòng trên 1 trang hoặc tổng giá trị các tất cả các trang. Bài viết dưới đây sẽ hướng dẫn các bạn thực hiện được điều này.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




- B1: Download CSDL Northwind

- B2: Sửa stored procedure trong SQL ServerDownload CSDL Northwind 

ALTER PROCEDURE [dbo].[CustOrdersDetail]
      @Keyword nvarchar(250),
      @OrderID int
AS
SELECT Top 100 ProductName,
    C.CategoryName,
    UnitPrice=ROUND(Od.UnitPrice, 2),
    Quantity,
    Discount=CONVERT(int, Discount * 100),
    ExtendedPrice=ROUND(CONVERT(money, Quantity * (1 - Discount) * Od.UnitPrice), 2)
FROM Products P, [Order Details] Od, Categories C
WHERE Od.ProductID = P.ProductID And P.CategoryID =C.CategoryID
And (@Keyword='' Or ProductName Like N'%'+ @Keyword+ '%')
And (@OrderID=-1 Or Od.OrderID = @OrderID)
ORDER BY ExtendedPrice DESC

Go

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây


B3: 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.

Imports System.Data.SqlClient
Imports System.Data

Namespace DisplayingTotalFooterGridView

    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 ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If Not Para Is Nothing Then
                    For Each p As ObjectPara In Para
                        adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
                    Next
                End If
                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

B4: Mở file Default.aspxdưới dạng HTML và  nhập mã HTML

<%@ Page Title="Displaying Total in Footer of GridView" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="DisplayingTotalFooterGridView._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Displaying Total in Footer of GridView
    </h3>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td>
                      
                    </td>
                    <td align="right">
                        <asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
                        <asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
                        <asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
                    </td>
                </tr>
                <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" AllowSorting="true" ShowFooter="true"
                            CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
                            BorderWidth="1" AutoGenerateColumns="false" width="100%">
                            <AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <RowStyle CssClass="GridStyle_RowStyle" />
                            <Pagerstyle cssclass="GridStyle_pagination" />
                            <FooterStyle CssClass="GridStyle_FooterStyle" />
                            <Columns>
                                <asp:TemplateField HeaderText="Number">
                                    <ItemStyle HorizontalAlign="Center" Width="2%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField ItemStyle-Width="18%" DataField="ProductName" HeaderText="ProductName"  />
                                <asp:BoundField ItemStyle-Width="15%" DataField="CategoryName" HeaderText="CategoryName"  />
                                <asp:BoundField ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Right" DataField="UnitPrice" HeaderText="UnitPrice" />
                                <asp:BoundField ItemStyle-Width="8%" ItemStyle-HorizontalAlign="Right" DataField="Quantity" HeaderText="Quantity"  />
                                <asp:BoundField ItemStyle-Width="8%" ItemStyle-HorizontalAlign="Right" DataField="Discount" HeaderText="Discount" />
                                <asp:TemplateField HeaderText="Discount">
                                    <ItemStyle HorizontalAlign="Right" Width="10%"></ItemStyle>
                                    <FooterStyle HorizontalAlign="Center"></FooterStyle>
                                    <ItemTemplate><%# Eval("Discount")%></ItemTemplate>
                                    <FooterTemplate>
                                        <asp:Label ID="plPageTotal" Text="Page Total" runat="server" ></asp:Label>
                                        <asp:Label ID="plGrandTotal" Text="Grand Total" runat="server" />
                                    </FooterTemplate>
                                </asp:TemplateField>                   
                                <asp:TemplateField HeaderText="ExtendedPrice">
                                    <ItemStyle HorizontalAlign="Right" Width="12%"></ItemStyle>
                                    <FooterStyle HorizontalAlign="Right"></FooterStyle>
                                    <ItemTemplate><%# Eval("ExtendedPrice")%></ItemTemplate>
                                    <FooterTemplate>
                                        <asp:Label ID="lblPageTotal" runat="server" />
                                        <asp:Label ID="lblGrandTotal" runat="server" />
                                    </FooterTemplate>
                                </asp:TemplateField>                         
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B5: Viết Code cho file Default.aspx

'Visit http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials
Imports System.Data.SqlClient

Namespace DisplayingTotalFooterGridView

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private PageTotal_ExtendedPrice As Decimal = 0
        Private GrandTotal_ExtendedPrice As Decimal = 0

#End Region

#Region "Bind Data"

        Private Sub BindOrdersDetail()
            Dim objBind As New DataTable

            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    GrandTotal_ExtendedPrice = objBind.AsEnumerable().Sum(Function(row) row.Field(Of Decimal)("ExtendedPrice"))
                    grvObject.DataSource = objBind
                    grvObject.DataBind()
                    trMessage.Visible = False
                    grvObject.Visible = True
                Else
                    trMessage.Visible = True
                    grvObject.Visible = False
                End If
                updatePanel.Update()
            End If
        End Sub

        Private Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("CustOrdersDetail", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
                                                                          New ObjectPara("@OrderID", -1))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        Private Sub grvObject_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                Dim ExtendedPrice As Integer = DataBinder.Eval(e.Row.DataItem, "ExtendedPrice")
                PageTotal_ExtendedPrice += ExtendedPrice
            End If

            If e.Row.RowType = DataControlRowType.Footer Then
                Dim intMergeCol As Integer = e.Row.Cells.Count - 1
                Dim intCellCol As Integer = 1
                For intCellCol = 1 To intMergeCol - 2
                    e.Row.Cells.RemoveAt(1)
                Next
                e.Row.Cells(0).ColumnSpan = 6

                Dim lblPageTotal As Label = CType(e.Row.FindControl("lblPageTotal"), Label)
                If Not lblPageTotal Is Nothing Then
                    lblPageTotal.Text = PageTotal_ExtendedPrice.ToString("N2")
                End If

                Dim lblGrandTotal As Label = CType(e.Row.FindControl("lblGrandTotal"), Label)
                If Not lblGrandTotal Is Nothing Then
                    lblGrandTotal.Text = GrandTotal_ExtendedPrice.ToString("N2")
                End If
            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
            BindOrdersDetail()
        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
                    'Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID
                    BindOrdersDetail()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdQuickSearch.Click
            BindOrdersDetail()
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.


Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Hiển thị tổng (Total) trong Footer của Gridview "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM