Calculate the Total of a particular column values in a DataGrid in ASP.NET using VB.NET

This article shows how we can get the sum of a given column of a DataGrid.
  • 5467
Download Files:
 

In this article, I am going to show how we can add a column value in a DataGrid. To add a column value in this programmed I am using a function. In the function, I am passing the value of that particular column. Let us see how to do this through the below code.

The default.aspx code is

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Get The Sum Of Particular Column In A DataGrid</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

     <asp:DataGrid id="MyGrid" runat="server"   AutoGenerateColumns="False" CellPadding="2"

            CellSpacing="0"   BorderStyle="Solid" BorderWidth="4" Gridlines="Both"

            BorderColor="ActiveCaption"   ItemStyle-Font-Name="Verdana" ItemStyle-Font-Size="10pt" 

             HeaderStyle-Font-Name="Verdana" HeaderStyle-Font-Size="14pt"   HeaderStyle-Font-Bold="True"

              HeaderStyle-BackColor="#ccffcc" FooterStyle-Font-Name="Verdana" FooterStyle-Font-Size="10pt"

               FooterStyle-Font-Bold="True"   FooterStyle-ForeColor="White" FooterStyle-BackColor="Blue"

               OnItemDataBound="MyDataGrid_ItemDataBound" ShowFooter="True">

             <Columns>

                <asp:BoundColumn HeaderText="Product ID" DataField="ProductID" />

                <asp:BoundColumn HeaderText="Product Name" DataField="ProductName"/>

                <asp:BoundColumn HeaderText="Unit In Price" DataField="UnitPrice"

                     ItemStyle-HorizontalAlign="center"  > </asp:BoundColumn>

                <asp:BoundColumn HeaderText="Units In Stock" DataField="UnitsInStock"

                 ItemStyle-HorizontalAlign="center" HeaderStyle-HorizontalAlign="Center" >

                </asp:BoundColumn>

            </Columns>

        </asp:DataGrid>

    </div>

    </form>

</body>

</html>


The Default.aspx.vb

Imports System

Imports System.Data

Imports System.Data.SqlClient

 

Partial Class _Default

    Inherits System.Web.UI.Page
 

    Dim TotalUnit As Integer

    Dim con As SqlConnection

    Dim cmd As SqlCommand
 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 

        con = New SqlConnection("server=Localhost; database=Northwind; uid=sa;pwd=;")

        cmd = New SqlCommand("SELECT ProductID, ProductName,UnitPrice, UnitsInStock  FROM Products WHERE UnitPrice > 30", con)

        Try

            con.Open()

            MyGrid.DataSource = cmd.ExecuteReader

            MyGrid.DataBind()

            con.Close()
       
Catch ex As Exception

            HttpContext.Current.Response.Write(ex.ToString())
       
End Try
    End Sub
 

    'This Method Will calculate the Column Value

    Private Sub MyTotalUnit(ByVal Unit As String)
 

        Try

            TotalUnit += [Double].Parse(Unit)

        Catch ex As Exception

            'A value was null

        End Try

    End Sub
 

    'Here we are binding the Data to the DataGrid

    Public Sub MyDataGrid_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
 

        If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then

            'Here we are passing the value of column in MyTotalUnit function to total

            MyTotalUnit(e.Item.Cells(3).Text)

            e.Item.Cells(3).Text = String.Format("{0:0}", Convert.ToDouble(e.Item.Cells(3).Text))

        ElseIf e.Item.ItemType = ListItemType.Footer Then

            e.Item.Cells(0).Text = "Total"

            e.Item.Cells(3).Text = String.Format("{0:0}", TotalUnit)

        End If

    End Sub

End Class


When user run the application then the window will look like this:


Image1.jpg


NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/).

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.