2017-08-30 91 views
0

我想要在Gridview中查找總價格,但是當我這樣做時,我必須跟蹤該部分。例如,如果我買了4雙鞋子,而且1雙鞋子的價格是20,那麼總價格應該是20 * 4。我怎樣才能做到這一點在GridView控件我怎樣才能計算在GridView的總價格在ASP.NET中

decimal price = 0; 
int piece = 0; 
decimal totalPrice = 0; 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     price += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "price")); 
     piece += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "piece")); 
     totalPrice = price * piece; 
    } 
    else if(e.Row.RowType == DataControlRowType.Footer) 
    { 
     e.Row.Cells[1].Text = "Total Price:"; 
     e.Row.Cells[2].Text = totalPrice.ToString("c"); 
     e.Row.Cells[1].HorizontalAlign = e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right; 
     e.Row.Font.Bold = true; 
    } 
} 
+0

在GridView的RowDataBound事件中,您可以從您的數據源中獲取價格和數量,然後乘以它並使用它。請在您的問題中包含代碼部分,以及您面臨的問題。 –

+0

我在後面加入了我的代碼。你可以檢查嗎? – Shadouspan

回答

1

你可以簡單地做到這一點,以顯示頁腳總。這裏我簡單地省略了異常處理。

decimal price = 0; 
int piece = 0; 
decimal totalPrice = 0; 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // This will multiply the price and piece and add it to final total. 
     totalPrice += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "price")) * Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "piece")); 
    } 
    else if(e.Row.RowType == DataControlRowType.Footer) 
    { 
     e.Row.Cells[1].Text = "Total Price:"; 
     e.Row.Cells[2].Text = totalPrice.ToString("c"); 
     e.Row.Cells[1].HorizontalAlign = e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right; 
     e.Row.Font.Bold = true; 
    } 
}