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

6
我在一个.NET 3.5 (Visual Studio 2008) WinForms应用程序中使用只读模式的DataGridView。
单元格的宽度非常小。有些单元格包含短数字。即使使用小字体,有时数字也会显示省略号。例如,"8..."而不是"88"。
是否有一种方法让文本在标准DataGridView中流动到下一个单元格,避免省略号?
谢谢!
5个回答

4

在设计师中更改DataGridView属性"RowDefaultCellStyle" -> 设置"换行模式"="true"


3
处理 DataGridView 控件的 CellPainting 事件。请查看以下链接:

http://msdn.microsoft.com/en-us/library/hta8z9sz.aspx

请注意,在绘制文本本身时,您需要自定义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;

问候


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;
}

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


1

一个可能适用于您的简单技巧就是将所需单元格的WrapMode设置为打开状态


1

不,可能有一些属性可以禁用省略号(如果访问底层控件),但普通DataGridView不支持流动和单元格合并。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接