How to Display Sum Total in the Footer of the GridView Control

I found an answer for this question. "How to Display Sum Total in the Footer of the GridView Control"

But this resource was written in aspx source. I wanted to convert this to "Code Behind" style but it's not working out. Please help me.

[Original working source]  aspx 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">
    Dim TotalUnitPrice As Decimal = 0.0
    Function GetUnitPrice(ByVal Price As Decimal) As Decimal
        TotalUnitPrice += Price
        Return Price
    End Function
    Function GetTotal() As Decimal
        Return TotalUnitPrice
    End Function

   
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" ShowFooter="true" DataKeyNames="ProductId" AutoGenerateColumns="false"
            runat="server" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="Productid" HeaderText="Product Id" />
                <asp:BoundField DataField="ProductName" FooterText="Total" HeaderText="Product Name" />
                <asp:TemplateField HeaderText="Unit Price" FooterStyle-Font-Bold="True">
                    <ItemTemplate>
                        <%# GetUnitPrice(decimal.Parse(Eval("UnitPrice").ToString())).ToString("N2")  %>
                    </ItemTemplate>
                    <FooterTemplate>
                        <%# GetTotal().ToString("N2") %>
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DummyDB %>"
            SelectCommand="Select * from Products"></asp:SqlDataSource>
    </form>
</body>
</html>
[Converted not working source] aspx
<%@ Page Language="VB" CodeFile="GV2.aspx.vb" Inherits="GV2" Debug="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" ShowFooter="true" DataKeyNames="ProductId" AutoGenerateColumns="false"
            runat="server" DataSourceID="SqlDataSource1" AllowSorting="true">
            
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DummyDB %>"
            SelectCommand="Select * from Products"></asp:SqlDataSource>
    </form>
</body>
</html>

 

[Converted not working source] aspx.vb

 

 
Partial Class GV2
    Inherits System.Web.UI.Page
    Dim TotalUnitPrice As Decimal = 0.0
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim col1 As BoundField = New BoundField()
        Dim col2 As BoundField = New BoundField()
        Dim col3 As TemplateField = New TemplateField()


        col1.DataField = "Productid"
        col1.HeaderText = "Product Id"
        col1.SortExpression = "Productid"

        col2.DataField = "ProductName"
        col2.HeaderText = "Product Name"
        col2.FooterText = "Total"

        col3.HeaderText = "Unit Price"
        col3.ItemTemplate() = GetUnitPrice(Decimal.Parse(Eval("UnitPrice").ToString())).ToString("N2")
        col3.FooterTemplate = GetTotal().ToString("N2")

        GridView1.Columns.Add(col1)
        GridView1.Columns.Add(col2)
        GridView1.Columns.Add(col3)

   

    End Sub

    Function GetUnitPrice(ByVal Price As Decimal) As Decimal
        TotalUnitPrice += Price
        Return Price
    End Function
    Function GetTotal() As Decimal
        Return TotalUnitPrice
    End Function

End Class

 

[Error Message I get]

Server Error in '/ASPAllianceGVFooterTotal' Application.

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

 

I don't know what's wrong with the code. Please help!


Yjkim
0
yjkim
6/9/2006 3:54:10 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

8 Replies
1366 Views

Similar Articles

[PageSpeed] 35

Here is a sample of one that I did.

Private Sub dgCart_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgCart.ItemDataBound

      Select Case e.Item.ItemType

         Case ListItemType.AlternatingItem, ListItemType.Item

            'Calculate extprice field for each row and alternating row.

            myTotal +=

CDbl(e.Item.Cells(12).Text)

         Case ListItemType.Footer

            'Use footer to display the summary row

            e.Item.Cells(11).Text = "Cart Total: "

            e.Item.Cells(12).Text = myTotal.ToString("c")

      End Select

End Sub
0
defuser
6/9/2006 7:21:47 PM

Thank you for the quick reply.

But I don't actually understand it especially in C#.

Can you please check out these source code?

Here's the link for the source code GV2.aspx, GV2.aspx.vb, Web.config

http://www.wizbay.com/sample.zip

Since it's using northwind db, you don't need to change any setting. It should work beside the problem I have in VB code.

 

Thank you for your help. I really appriciate you. 

0
wizbay
6/9/2006 7:56:18 PM

Just in case, I am attaching the working version source code.

GV2.aspx, Web.config

http://www.wizbay.com/Sample(original).zip

 

Thank you.

 

0
wizbay
6/9/2006 8:00:21 PM

My sample is not written in C# it is VB.

mytotal is a varible declared earlier.  All I am doing is reading the value from the databound column of the line item total and and adding it to the previous values (i.e. mytotal +=).

Then when it get to the footer I am adding text in one cell and the value of mytotal in the next one.

hope this explains it a little better.

 

0
defuser
6/12/2006 6:12:59 PM
Sorry, the summing of mytotal is: mytotal += CDbl(e.Item.Cells(12).Text)
0
defuser
6/12/2006 6:15:37 PM

I added your sample to my VB page but it's not recognizing dgCart.

Your sample needs to be added in my VB page right?

0
wizbay
6/12/2006 6:38:42 PM

You should create a datagrid or dataview and and set up the datasource bindings as normal.  In the code-behind page you would add the code sample I gave you.  But you need to make needed changes to correspond to your naming scheme.  Then it should work.  The sample I provided was not meant to be a cut and paste.  Just a sample to get you headed in the right direction.  I am not positive that this will work in a GridView but it does in a DataGrid.  Also, I don't see where you are getting the data from.  I don't see a datasource in the "[Converted not working source] aspx.vb" code.  From what I can tell of your code it would look something like this:

Private Sub GridView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles GridView1.ItemDataBound

Dim myTotal as Double

      Select Case e.Item.ItemType

         Case ListItemType.AlternatingItem, ListItemType.Item

            'Calculate extprice field for each row and alternating row.

            myTotal +=

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

         Case ListItemType.Footer

            'Use footer to display the summary row

            e.Item.Cells(2).Text = "Cart Total: "

            e.Item.Cells(3).Text = myTotal.ToString("c")

      End Select

End Sub
0
defuser
6/12/2006 7:24:11 PM
I finally got it working. Thank you for your help, defuser!
0
wizbay
6/12/2006 9:10:45 PM
Reply:

Similar Artilces:

How to Display Sum Total in the Footer of the GridView Control using boundfield, templatefield
 This vb code compiles find but give me runtime error. Please help me!    Dim TotalUnitPrice As Decimal = 0.0 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim col1 As BoundField = New BoundField() Dim col2 As BoundField = New BoundField() Dim col3 As TemplateField = New TemplateField() col1.DataField = "Productid" col1.HeaderText = "Product Id" col1.SortExpression = "Productid" col2.DataField = "ProductName" col2.HeaderText = "Product N...

Menu control is displaying behind Gridview control
I have placed a menu control just above the gridview control but when i click the menu control it displaysome of the menu options and rest of the menu options display behind the gridview.Is there anyway any option which make the menu to display over gridview.Mark as answer if anybody's post has helped you Typically the ZIndex will control that: http://www.w3schools.com/Css/pr_pos_z-index.aspDavid Kiffhttp://DavidKiff.co.uk-- "Mark As Answer" If my reply helped you --...

gridview control in another gridview control
Hi ia have a questioni have a gridview control which contains button in one colum.now my question is i need another gridview to be placed in the  first gidviewso that when i click on the button the second gridview will populate the data.now my question is how to place second gridview in first gridview.or is there any approach like first grid itself acting as parent and child.please help me  Hi sirikalavalapalli:                I think nested gridview will help you. Check this link and it will show you how...

Footer not displaying in gridview control....
I am trying to make the footer display that is discused in the example in the link belowDisplaying Summary Data in the Footer I put a breakpoint in the code below and watched the footer values get set but a footer row is never displayed.  What is not set correctly? protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) {totalPrice = totalPrice + Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "UnitPrice"));totalQuantity = totalQuantity + Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, ...

Getting the control id of a control inside gridview control
 uhmm.. a little bit confusing regarding my subject because i dont know how to say it...by the way my problem is how can i get the id of a control (e.g. textbox) inside the gridview... and the textbox is in the templatefield... is there any way i can get its id??  hoping i could get a reply as soon as possible... Regards,MhaeyPlease remember to click “Mark as Answer” on the post that helps you.. =) What do you want's to do by getting the id of the Text box? Do you want's to find particular Textbox with certain id ? Kamran ShahidSr. Software Engineer(MCP,MCAD.net,MC...

Gridview control embedded in another gridview control
I am writing an ambulance crew scheduling application on the web and I need some help completing the last part.  I have an access database that has three tables: user table, shift table (describing the shifts available), and a schedule table (that stores shift by shift_id and user by user_id).  I have a gridview control that will display the available shifts but I cannot get the embedded gridview control that will display the user that is signed up for each shift to display because I cannot figure out how to use the OnRowDataBound method.  I need a simple VB example of how to...

Help Req: !!! :- On Disabling Controls Present inside a Gridview control
Hi All, We have A requirement Where we have disable controls inside a grid.These controls can be textbox, DropDownlist (in TemplateField), ComandField present inside the grid.We have to call a generic method for doing the same .(since it can be done for multiple grid.) PFB the code snippet we use. Which disables all the controls inside the page.The bolded part of the code is used to loop inside a grid view.(Not Working.)Is this ideal way to deal with the requirement.Or can someone suggest be a better way.        public void DisableMe(Page p1, st...

Data presentation control in another Data presentation control
 Hello,I want to make a menu with datalist or gridview control.Basically,the menu will be like this,Categories     Sub Categories.For example, for COMPUTING category there will be NOTEBOOKS DESKTOPS etc.There will be a image for CATEGORIES and linkbuttons with Subcategories.If I put a datalist inside a datalist and a link button inside the second datalist visually it satisfies my need.However,CommandArguments come from database to linkbutton.Andwhen one of these command buttons is cliked it must go to proper page.I dont know how to wrie an event_handler ,specifically, for...

There is a Gridview Control in the tmplate field of another GridView Control.
    For instance,a gridview displays the information of the  students in a class.A table is recording the information except their mark.There is another table recording the mark of the students whose foreign key is the primary key of the previous table.   string strSQLconnection=".................."; SqlConnection sqlCononection=new SqlConnection(strSQLconnection); SqlCommand sqlCommand=new SqlCommand("select * from stuendent where classID=1",sqlConnection); SqlConnection.Open(); SqlDataReader reader=sqlCommand.ExecuteReader(); GridVie...

using controlS to control a gridview
This question is probably posted but i did not bother to look at 10,000+ posts so i am sorry. I've seen the tutorial where he builds a dataset and uses a gridview and controls the gridview with the drop down list box. What i am trying to do is to control the gridview with 2 drop down list boxes. First select the Country you life in and then the State. I've looked at the grid view properties but couldn't find where i can add another parameter. Is it possible to control a grid view (or any form of displaying the information) with more than 1 controller? Thank You.  ...

Validation controls displayed over other controls
Does anyone know of away to display a validation control on top of a dropdownlist? Or any other ideas on how to display an error message on top of a dropdownlist. I'm a novice at this so please don't get too deep in programming. Hi, first of all, most people are used to see validation controls, being it either in a web application or a winforms application, right of the control that needs attention. Being said that you could use the z-index of CSS to display a <span> or <div> tag above your control and put the validation control inside that html tag that you display above y...

validation controls in gridview control
hi, I m using the grid view to add,edit,update,delete the data table. Everything is fine.In the footertemplate i get the values through text boxes and drop down lists.i took place sm validation controls to validate these controls.the problem arises here.if i want to update the record after i click the edit button, it validate the page n dont allow me to update the record.I want to validate the particular controls only. i checked if any causes validation property for update button.there is nothing like that. pls help me.. thanks in advance gowri  regards,gowripillaimark as answer if...

Precise Control over GridView controls?
Hi.When you create a GridView in visual studios and bind it to, say, an SqlDataSource, it automatically creates fields and templates according to the types retrieved from the data source. (ie, it creates a Label for number/string columns, checkboxField for booleans, etc). My question: How do I control precisely what WebControls/Fields are used for each column?thanks,Tombow Hi Tombow Using TemplateFields you can control that explicitly.  See the Data Tutorial #12 at http://www.asp.net/learn/dataaccess/default.aspx?tabid=63 for more details. Hope that helps. AaronDon't...

SqlDataSource Control and Gridview control
Hi, I'm new to web development and learning about these controls.  The books teach you to bind the gridview control to an sqldatasource to perform delete,update,insert functions as well as to list the records in a table.  Is this standard practice for real world applications?  Or is there another way that should be used to display/manage table data in the gridview control? Thanks. Tulsi Using a sqldatasource is the best way I know of for binding data to a gridview.  (I'm pretty new to web development too, so maybe someone else can chime in if they know someth...

Web resources about - How to Display Sum Total in the Footer of the GridView Control - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 11/27/2015 4:12:09 PM