Link to home
Start Free TrialLog in
Avatar of dizzycat
dizzycat

asked on

Calculated field in a gridview

Hi experts

Using asp.net 4 with either C# or vb.net as the code behind I want to have a calculated field in a gridview, i have researched how to do this and it seems there are several options, in my gridview amongst other fields i have:  Item_Price, Quantity and Total, i want the Total field to = the Item_Price * Quantity, the only bound field is the Item_Price the other two are Templates, i have tried using:

<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label Text='<% Eval ("Item_Price") * Eval ("Quantity") %>'
runat="server"/>
</ItemTemplate>
</asp:TemplateField>



This does not work though, ideally I would like a checkbox in the gridview to trigger the calculation.
Hope somebody can help
Avatar of gingermoleman
gingermoleman

Hi,

A couple of different approaches you could take. You could do the sum in your SQL query and return it as its own field

ie

SELECT  ([item_price] * [Quantity]) as total
but this would require holding the quantity in the DB

If quantity is a user entered value then you can do it this way

in the grid view:

           <asp:TemplateField HeaderText="Total" SortExpression="Total">
            <ItemTemplate>
        <asp:Label ID="TotalLabel" runat="server" Text='<%#calcTotal (# Bind("DBID"),# Bind("DBID"))%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

this calls a function called calcTotal and passes it the two values, in your code behind you need to add the function:

Function calcTotal(ByVal value1 As Decimal, ByVal value2 As Decimal)
        Return value1 * value2
    End Function

Let me know if you need more help.

GMM
ASKER CERTIFIED SOLUTION
Avatar of JosephEricDavis
JosephEricDavis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dizzycat

ASKER

I am using code below:

<asp:TemplateField HeaderText="Total">
                <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%#calcTotal(#Bind("Quantity"),#Bind("Price"))%>'></asp:Label>
                </ItemTemplate>

But getting error message:

Preprocessor directives must appear as the first non whitespace character on a line.

Any ideas
Can you copy and past the first few lines of your aspx file here?
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!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></title>
</head>
Yeah, I'm not sure.

But again, I would call your attention to my earlier post as another course of action.  Whenever you use code like this

<%# blah blah blah %>

You are including in your aspx page code that is intended to go into your code behind.  This is usually fine, but at the end of the day it is not a best practice as it is not separating your presentation layer from your business logic.

Before you try this you might try removing the server side include in the label to see if the error continues to happen, just to verify what is actually causing your error.

<asp:Label ID="TotalLabel" runat="server" Text='testing'>
Did you convert the function to c# (mine was VB)

public object calcTotal(decimal value1, decimal value2)
{
      return value1 * value2;
}

though I have to say that Josephs suggestion is probably the better one to learn as there is lots more you can do in the rowDataBound event (where as mine just multiplies)

GMM
Hi,

Try this
<asp:Label ID="Label1" runat="server" Text='<%#calcTotal(Bind("Quantity"),Bind("Price"))%>'></asp:Label>

instead of this
<asp:Label ID="Label1" runat="server" Text='<%#calcTotal(#Bind("Quantity"),#Bind("Price"))%>'></asp:Label>


my fault, I wrote the original bit out without actually testing it, you dont want the extra #'s



GMM
I've done what you said GMM

But now getting 2 errors both saying:

The name Bind does not exist in the current context

This is my C# code behind:

public object calcTotal(decimal Quantity, decimal Price)
    {
        return Quantity * Price;
    }
A quick question to Joseph:

You used the OnRowDataBound event, I can only find the RowDataBound event, are they the same?
OnRowDataBound should be one of the available options provided by intellisense when you are inside the <asp:GridView> tag.  I just double checked on a working example that I have locally and it definitely has the 'On' as part of the property name.

If you don't have it as part of your intellisense list, I would try to go ahead and just type it in like I have it and see what happens.
Hi,

its definately has the 'on' bit and Josephs solutions does the job perfectly. Bit baffled by the errors your getting from mine, I can recreate them all! works a treat when coded in VB though.

GMM
Got it working.

I think I will stick to using the code behind file as much as possible in the future, as you say keep the two layers separate. I'm sure I will be back asking more questions about manipulating a gridviews data very soon, but until then thanks for your help.
The code you'd written in question is correct, it should work. It's working in my project too.

<asp:TemplateField HeaderText="Total">
 <ItemTemplate>
  <asp:Label Text='<% Eval ("Item_Price") * Eval ("Quantity") %>' runat="server"/>
 </ItemTemplate>
</asp:TemplateField>

Open in new window


But the problem is with next requirement (CheckBox column), I'm writting following code which should work with CheckBox, which should work.

<asp:GridView runat="server" ID="GC" AutoGenerateColumns=false>
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox runat="server" ID="CB" AutoPostBack="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Item_Price" HeaderText="Item Price" />
                <asp:TemplateField HeaderText="Quantity">
                    <ItemTemplate>
                        <asp:Label runat="server" Text='<%# Eval("Quantity") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total">
                    <ItemTemplate>
                        <asp:Label runat="server" Text='<%# if(CType(CType(Container, GridViewRow).FindControl("CB"), CheckBox).Checked,  Eval("Quantity") * Eval("Item_Price"),0) %>' />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Open in new window


 Now The problem comes, In gridview if we add a checkbox in template column with AutoPostBack="true". Now if we mark it checked in runtime then after postback it'll uncheck automatically, If somehow you make its state persisted, then your work'll be done.
Problem is with checkbox, not with CalculatedColumn