c# - 如何在 DataGridView 中不带空格地换行文本 (vb.net/c#)

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

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

但是这个 WrapMode 不会用没有空格的单个单词来换行。有什么方法可以让我们与 WrapMode 一起“断词”?或者任何其他解决方案?

最佳答案

您可以使用 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;因此您还将知道该 Cell 所需的 Height。将它与当前的 Row.Height 进行比较,您可以逐渐为每个 Row 调整它,即在每次需要时将其变大。我没有包括在内,因为它将导致 Rows 具有不同的高度,这在您的情况下可能是不需要的/不必要的。不过,如果您有兴趣,我可以发布代码......

enter image description here

关于c# - 如何在 DataGridView 中不带空格地换行文本 (vb.net/c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067650/

相关文章:

c# - 没有 ID 和名称的 GetElementById 如何?

c# - System.Drawing Bitmap 给出了错误的尺寸

ajax - 在 VB.NET 中将实例传递给共享方法

VB.NET 动态 API 调用 x64

.net - 如何在 VB.NET 中使用#IF DEBUG

c# - 绑定(bind)到 UserControl 中的 DataGrid ItemSsource

c# - 如何配置 ASP.NET 应用程序的环境?

.net - 为什么是程序集 .exe 文件?

.net - Axum vs TPL,异步

c# - 处理 AppDomain.CurrentDomain.UnhandledException 中的异常