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

.net 如何在WindowsForms DataGridView中禁用单元格文本的省略号?,.net,winforms,datagridview,ellipsis,.net,Winforms,Datagridview,Ellipsis,我在.NET3.5(VisualStudio2008)WinForms应用程序中有一个只读模式的DataGridView 细胞的宽度很小。有些单元格包含短数字。现在,即使使用小字体,有时数字也会显示为省略号。例如,“8…”而不是“88” 有没有办法让文本在标准DataGridView中的下一个单元格上流动并避免省略号 谢谢 否,可能有一些属性可以禁用省略号(如果您访问基础控件),但标准DataGridView中不支持溢出(以及单元格合并)。处理DataGridView控件的单元格绘制事件。 检查

我在.NET3.5(VisualStudio2008)WinForms应用程序中有一个只读模式的DataGridView

细胞的宽度很小。有些单元格包含短数字。现在,即使使用小字体,有时数字也会显示为省略号。例如,“8…”而不是“88”

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


谢谢

否,可能有一些属性可以禁用省略号(如果您访问基础控件),但标准DataGridView中不支持溢出(以及单元格合并)。

处理DataGridView控件的单元格绘制事件。 检查以下链接:

请注意,在绘制文本本身时,需要自定义StringFormat-

引用MSDN代码:

if (e.Value != null)
{
    e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
                    Brushes.Crimson, e.CellBounds.X + 2,
                    e.CellBounds.Y + 2, StringFormat.GenericDefault);
}
使用以下StringFormat对象代替StringFormat.GenericDefault:

StringFormat strFormat = new StringFormat();
strFormat.Trimming = StringTrimming.None;

关于

一个可能对您有效的简单技术就是在Designer更改DataGridView属性“RowDefaultCellStyle”->设置“Wrap Mode”=“true”

中为相关单元格启用WrapMode。为了这么小的改变而完全重新实现单元格绘制似乎很愚蠢——处理列标题和选定行的绘制也需要大量的工作。幸运的是,有一个更整洁的解决方案:

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