如何在DataGridView中包装没有空格的文本(vb.net / c#)

时间:2014-09-26 20:15:15

标签: c# .net vb.net datagridview word-wrap

我已经设置了DataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True

但是这个WrapMode不会用单个单词包装没有空格的列。有什么方法我们可以"破解"和WrapMode一起?还是其他任何解决方案?

2 个答案:

答案 0 :(得分:2)

您可以使用CellPainting事件。

DrawString尊重边界Rectangle并在任何到达右边界的地方包裹。

您可以取消注释条件以仅应用于超出您设置限制的单元格。 为了获得最佳控制,您必须测量FormattedValue的长度以找出确切的限制。

如果细胞中有特殊的比对,您可能还需要微调绘制位置。

private void DGV1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.Value == null) return;
    if (e.FormattedValue.GetType() != typeof( System.String) ) return;
    bool selected = (e.State & DataGridViewElementStates.Selected) 
                            == DataGridViewElementStates.Selected;
    string s = e.FormattedValue.ToString();

    //if (s.Length > 20) // Apply to all or only those breaking your limits
    {
        e.PaintBackground(e.CellBounds, selected);
        e.Graphics.DrawString(s, DGV1.Font, selected ? 
                   SystemBrushes.HighlightText : SystemBrushes.ControlText, 
                   new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 2, 
                                 e.CellBounds.Width - 2, e.CellBounds.Height - 4));
        e.Handled = true;
    }
}

设置Row.Heights取决于您。如果你去测量FormattedValue,你会得到一个RectangleF;因此,您也知道Height所需的Cell。将其与当前Row.Height进行比较,您可以逐步调整每个Row,即每次必要时将其调整得更大..我没有包括,因为它会导致行变化在您的情况下,高度可能是不需要/不必要的。如果您有兴趣,我可以发布代码,但是..

enter image description here

答案 1 :(得分:0)

hi Shimply在DataBinding之后添加以下行

DGLogs.Columns[0].DefaultCellStyle.WrapMode=DataGridViewTriState.True;

set
AutosizecolumnMode=AllCells
AutosizeRowMode=AllCells
属性窗口中的

输出将如同所示 enter image description here

相关问题