开发者

Calculate Total Value In Gridview In ASP.net C#

I am using a website which contains a gridview for view details of Product details... It contains columns like name,area,phnoe no,quantity,price,total.... now I want to cal开发者_C百科culate total value for that I have to multiply the columns quantity and Price and also put that answer to total column in grid... How shall I do this?


There are three(may be more) ways to accomplish this.
First is query database and show result on grid

To do this : Query like
select name,area,phone,quantity,price,quantity * price as Total from YOUR_TABLE Then bind it into your datagrid

Second is before binding your source which is here datatable into the grid,loop for this table for your sum.

To do this: You have datatable but not you have column named Total this time.
Now you need to add a new column as Total into the datatable.

DataColumn totalColumn = new DataColumn("Total");
totalColumn.Expression = "Quantity * Price";
totalColumn.DataType = //double,integer 
dataTable.Columns.AddAt(totalColumn, 0);

All we have done above is generating a computed column

Third,use javascript for cells to assemble your specific values to sum,but this time you need to find your datagrid then your cells in which you should prefer using a javascript framework like jquery.I do not know any reference point for this,but First and second options will be much easier to do


Best Regards
Myra


Its simple yaar, if the row index is 0 and your column name in price means ,the following is the way to getvalues, GridViewID.Rows[0].cells["Price"].ToString()


It depends on your requirement/ wish, you can use Javascript to calculate total on client side if you are not fetching data from database.

You can also do it in code behind but it would be better to use JQuery to fetch the data and calculate it on client side.


but i have to it in code behind only

Ok then. You need to a template column to your GridView

<asp:TemplateField>
<ItemTemplate>
  <asp:Literal ID="litTotal" runat="server" />
</ItemTemplate>
</asp:TemplateField>

Subscribe to the RowDataBound Event.

protected void grid_RowDataBound(object sender, GridViewRowEventArgs e) 
{    
 if(e.Row.RowType == RowType.DataRow)  
 {  
    YourObject _item = (YourObject)e.Row.DataItem; // use quickwatch to figure out how to cast into your desired type
    Literal _litTotal = (Literal)e.Row.FindControl("litTotal");
  _litTotal.Text = _item.Quantity * _item.Price;
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜