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

DataGridView绘制字符串时行自动调整大小失效问题

DataGridView自定义绘制多行文本时自动调整行高的解决办法

GetPreferredHeight返回固定20是因为它基于单元格默认文本渲染逻辑计算,完全不知道你在CellPainting事件里自定义的多行文本内容和排版规则,得手动计算文本的实际渲染高度。

步骤1:实现文本高度计算方法

这个方法会根据单元格宽度、使用的字体,计算文本换行后的真实高度:

private int CalculateTextHeight(string text, int cellWidth, Font font)
{
    if (string.IsNullOrEmpty(text)) return 20; // 空文本返回默认高度
    using (var g = Graphics.FromHwnd(dataGridView1.Handle))
    {
        // MeasureString自动计算换行后的文本尺寸
        var textSize = g.MeasureString(text, font, cellWidth);
        return (int)Math.Ceiling(textSize.Height);
    }
}

步骤2:批量或实时调整行高

场景1:加载数据后批量调整

一次性加载数据后统一调整行高,遍历所有行计算:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (!row.IsNewRow)
    {
        // 替换成你实际要计算的列索引
        int targetColumnIndex = 0;
        string cellText = row.Cells[targetColumnIndex].Value?.ToString() ?? "";
        int cellWidth = dataGridView1.Columns[targetColumnIndex].Width;
        int requiredHeight = CalculateTextHeight(cellText, cellWidth, dataGridView1.Font);
        
        // 取当前行高和计算高度的最大值,避免覆盖其他单元格需要的高度
        row.Height = Math.Max(row.Height, requiredHeight);
    }
}

场景2:单元格内容变化时实时调整

在CellValueChanged事件里触发行高更新:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
    
    var row = dataGridView1.Rows[e.RowIndex];
    string cellText = row.Cells[e.ColumnIndex].Value?.ToString() ?? "";
    int cellWidth = dataGridView1.Columns[e.ColumnIndex].Width;
    int requiredHeight = CalculateTextHeight(cellText, cellWidth, dataGridView1.Font);
    
    row.Height = Math.Max(row.Height, requiredHeight);
}

额外处理:列宽变化时重新计算

如果用户可能调整列宽,要在ColumnWidthChanged事件里重新计算对应行的高度:

private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (!row.IsNewRow)
        {
            string cellText = row.Cells[e.Column.Index].Value?.ToString() ?? "";
            int requiredHeight = CalculateTextHeight(cellText, e.Column.Width, dataGridView1.Font);
            row.Height = Math.Max(row.Height, requiredHeight);
        }
    }
}

注意事项

  • 如果在CellPainting里使用了自定义字体,记得把方法中的dataGridView1.Font替换成你自定义的字体对象。
  • 计算高度时用Math.Ceiling确保向上取整,避免文本被截断。

内容的提问来源于stack exchange,提问作者Adam The Nomad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:45:14