gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:09:19 29 4
gpt4 key购买 nike

我已经设置了 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com