常見的一個應用情境,就是gridview中,當庫存量少於某個數時,背景顏色先變色
還有就是對某一列統計其總和,顯示在頁尾裡,下面分別闡述之
首先是當庫存小於某個值時,行的背景顏色改變,比如
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// 確認"庫存量"欄位的值。
//
// 我們透過一個 DataBinder.Eval() 調用從將被綁定至 GridView 資料列的
// 資料中取得"庫存量"欄位的值,傳遞給 DataBinder.Eval() 的第一個參
// 數是將被綁定至 GridView 資料列的資料(也就是 e.Row.DataItem),
// 傳遞給 DataBinder.Eval() 的第二個參數則是欄位名稱。
decimal stock =
Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "庫存量"));
if (stock <= 0)
{
// 如果庫存量小於或等於 0,則將該資料列的背景色設定成紅色。
e.Row.BackColor = Color.Red;
}
decimal totalMoney =
Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "訂貨金額"));
if (totalMoney > 0)
{
// 如果訂貨金額大於 0,則將該資料列的背景色設定成黃色。
e.Row.BackColor = Color.Yellow;
}
// 累加訂貨金額並設定給變數 orderTotal。
orderTotal += totalMoney;
}
}
而在頁面中加入footer模版
<asp:TemplateField HeaderText="訂貨金額" SortExpression="訂貨金額">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("訂貨金額", "{0:c}") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="OrderTotalLabel" runat="server" Font-Underline="True" ForeColor="Red"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("訂貨金額", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
// 建立一個變數來儲存訂貨金額加總。
private decimal orderTotal = 0.0m;
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
// 提取當前的資料列。
GridViewRow row = e.Row;
// 如果正被建立的資料列是一個頁尾,則更新資料行加總。
if (row.RowType == DataControlRowType.Footer)
{
// 取得頁尾當中的標籤控制項 OrderTotalTotal 。
Label total = (Label)(e.Row.FindControl("OrderTotalLabel"));
// 以貨幣格式來顯示訂貨金額加總。
if (total != null)
{
total.Text = orderTotal.ToString("c");
}
}
}