Question

I have a GridView with 2 BoundFields like this:

<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price">
        </asp:BoundField>

<asp:BoundField DataField="Quantity" HeaderText="Quantity">
        </asp:BoundField>

How do I add a "Total" field which is calculated by multiplying the other 2 fields to the GridView declaratively? These 2 existing fields are from an SQL database and I cannot add new fields to this database. In a way, I must create the Total field dynamically.

If this is not possible, how to do this programmatically? Thanks.

Was it helpful?

Solution

Easiest way would be to add a property to the underlying class:

Decimal Total { get { return UnitPrice*Quantity; } }

You can then reference the field Total in a BoundField

If modifying the underlying class isn't an option, try this:

<asp:TemplateField>
   <ItemTemplate>
      <asp:Label runat="server" Text='<%# String.Format("{0:c}", ((Decimal)Eval("UnitPrice"))*((int)Eval("Quantity"))) %>' />
   </ItemTemplate>
</asp:TemplateField>

Note that you will want to make sure the casts for each Eval match your data structure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top