You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Visual Studio的DataGridView中使用多种字体?

解决DataGridView行字体差异化显示问题

Access数据库仅存储数据内容,不会保存字体这类UI显示属性,所以直接修改数据库设置无法实现行字体差异化,需在DataGridView的UI层面通过事件处理实现:

实现步骤

  1. 完成数据库数据与DataGridView的绑定后,注册CellFormatting事件(可通过设计器双击事件,或在代码中手动绑定)
  2. 在事件处理方法中,根据行索引或行内特定数据标识,为对应行设置目标字体

代码示例(按行索引设置)

// 手动绑定事件(可放在Form_Load方法中)
dataGridView1.CellFormatting += dataGridView1_CellFormatting;

// 事件处理方法
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 为第1行(索引0)设置SANS字体
    if (e.RowIndex == 0)
    {
        e.CellStyle.Font = new Font("SANS", 10);
    }
    // 为第2行(索引1)设置Tahoma字体
    else if (e.RowIndex == 1)
    {
        e.CellStyle.Font = new Font("Tahoma", 10);
    }
}

可选:按行数据标识设置

如果需要根据行内某个字段值动态判断字体(比如存在FontType字段),可修改事件逻辑:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var fontTypeCell = dataGridView1.Rows[e.RowIndex].Cells["FontType"];
    if (fontTypeCell.Value != null)
    {
        string fontType = fontTypeCell.Value.ToString();
        e.CellStyle.Font = fontType == "SANS" 
            ? new Font("SANS", 10) 
            : new Font("Tahoma", 10);
    }
}

注意事项

  • 确保系统中存在目标字体,否则会自动 fallback 到默认字体
  • 数据动态更新时,CellFormatting事件会自动触发,无需额外处理

内容的提问来源于stack exchange,提问作者Uhgb Bnj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:07:01