计算DataGridView中的行数

时间:2012-06-20 03:37:26

标签: c# datagridview

我正在使用DataGridView并设置:

AutoSizeRowsMode = DisplayedCell

&安培;

RowDefaultCellStyle: WrapText=True

结果:

enter image description here

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

图片:

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

1 个答案:

答案 0 :(得分: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;
}