0

我正在使用 DataGridView 并设置:

AutoSizeRowsMode = DisplayedCell

&

RowDefaultCellStyle: WrapText=True

结果:

在此处输入图像描述

如何获得具有行数 DataGridView 的订单。例如,在图片中。线= 8。

图片中:

Row1 = 2 Line & Row2 = 1 Line & Row3 = 4 Line & Row4 = 1 Line. -----> Line = 8
4

1 回答 1

2

您最好的选择是MeasureString()根据当前字体和单元格宽度使用。这是执行您想要的代码:

private int CountLines(DataGridView dataGridView)
{
    int totalLineCount = 0;
    using (Graphics graphics = Graphics.FromHwnd(this.Handle))
    {
        SizeF baselineSize = graphics.MeasureString("test line", dataGridView.Font);
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            int cellLineCount = 0;

            foreach (DataGridViewCell cell in row.Cells)
            {
                if (cell.Value == null)
                {
                    continue;
                }

                string value = cell.Value.ToString();
                SizeF size = graphics.MeasureString(value, dataGridView.Font, cell.Size.Width);
                int lines = (int)Math.Round(size.Height / baselineSize.Height);
                cellLineCount = Math.Max(cellLineCount, lines);
            }

            totalLineCount += cellLineCount;
        }
    }

    return totalLineCount;
}
于 2012-06-20T04:48:35.870 回答