如何在WindowsForms DataGridView中禁用单元格文本的省略号?

spl*_*tne 6 .net datagridview ellipsis winforms

我在.NET 3.5(Visual Studio 2008)WinForms应用程序中以只读模式使用DataGridView.

细胞的宽度非常小.一些单元格包含一个短数字.现在,即使使用小字体,有时数字也会以省略号显示.例如"8 ..."而不是"88".

有没有办法让文本流过标准DataGridView中的下一个单元格并避免省略号?

谢谢!

Oli*_*ver 2

我发现 KD2ND 此处给出的解决方案并不令人满意。对于如此小的更改完全重新实现单元格绘制似乎很愚蠢 - 处理列标题和选定行的绘制也需要大量工作。幸运的是,有一个更简洁的解决方案:

// you can also handle the CellPainting event for the grid rather than 
// creating a grid subclass as I have done here.
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
    var isSelected = e.State.HasFlag(DataGridViewElementStates.Selected);

    e.Paint(e.ClipBounds, DataGridViewPaintParts.Background
        //| DataGridViewPaintParts.Border
        //| DataGridViewPaintParts.ContentBackground
        //| DataGridViewPaintParts.ContentForeground
        | DataGridViewPaintParts.ErrorIcon
        | DataGridViewPaintParts.Focus
        | DataGridViewPaintParts.SelectionBackground);

    using (Brush foreBrush = new SolidBrush(e.CellStyle.ForeColor),
        selectedForeBrush = new SolidBrush(e.CellStyle.SelectionForeColor))
    {
        if (e.Value != null)
        {
            StringFormat strFormat = new StringFormat();
            strFormat.Trimming = StringTrimming.Character;
            var brush = isSelected ? selectedForeBrush : foreBrush;

            var fs = e.Graphics.MeasureString((string)e.Value, e.CellStyle.Font);
            var topPos= e.CellBounds.Top + ((e.CellBounds.Height - fs.Height) / 2);

            // I found that the cell text is drawn in the wrong position
            // for the first cell in the column header row, hence the 4px
            // adjustment
            var leftPos= e.CellBounds.X;
            if (e.RowIndex == -1 && e.ColumnIndex == 0) leftPos+= 4;

            e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
                brush, leftPos, topPos, strFormat);
        }
    }

    e.Paint(e.ClipBounds, DataGridViewPaintParts.Border);
    e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

诀窍是让现有的“Paint”方法处理大部分单元格的绘制。我们只处理文本的绘制。边框是在文本之后绘制的,因为我发现否则有时文本会被绘制在边框上,这看起来很糟糕。