首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# DataGridView 添加合計行與修改字體顏色的官方文檔指引

     編輯:程式設計綜合問答

需求

在 `DataGridView` 中:

  1. 添加一行「合計/統計」行(如求和、平均值)。
  2. 根據條件修改單元格/行的字體顏色。

官方最佳實踐參考

微軟官方文檔提供了完整示例:

DataGridView 控制項 - 自定義格式化與統計行(中文)

核心技術點摘要

1. 添加合計行

  • **方案 A**:數據源層面計算好統計行,作為一行數據綁定(最簡單)。
  • **方案 B**:使用 `RowsAdded`/`CellFormatting` 事件,動態插入只讀行並計算。
  • **方案 C**:繼承 `DataGridView` 重寫 `OnPaint`,底部繪製統計行(高級)。

2. 修改字體顏色

  • **CellFormatting 事件**:
    dataGridView1.CellFormatting += (s, e) => {
        if (e.ColumnIndex == 2 && e.Value != null) {
          int val = Convert.ToInt32(e.Value);
          e.CellStyle.ForeColor = val < 0 ? Color.Red : Color.Black;
        }
      };
  • **RowPrePaint 事件**:整行樣式控制。
  • **DataGridViewCellStyle**:統一設置 `ForeColor`、`BackColor`、`Font` 等。

快速入門代碼片段

// 綁定數據後,手動添加統計行
var dt = (DataTable)dataGridView1.DataSource;
DataRow sumRow = dt.NewRow();
sumRow["Name"] = "合計";
sumRow["Amount"] = dt.Compute("SUM(Amount)", "");
dt.Rows.Add(sumRow);

// 設置該行樣式
int lastRow = dataGridView1.Rows.Count - 1;
dataGridView1.Rows[lastRow].DefaultCellStyle.ForeColor = Color.Blue;
dataGridView1.Rows[lastRow].DefaultCellStyle.Font = new Font("微軟雅黑", 9, FontStyle.Bold);

建議

直接閱讀官方文檔(上方鏈接)可獲得最權威、最完整的示例與 API 說明,涵蓋虛擬模式、大數據優化、導出 Excel 等進階主題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved