首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在winforms (C#)的DataGridViewTextBoxCell中换行,不带空格或换行符?

如何在winforms (C#)的DataGridViewTextBoxCell中换行,不带空格或换行符?
EN

Stack Overflow用户
提问于 2012-01-19 15:35:11
回答 1查看 713关注 0票数 0

如何在DataGridViewTextBoxCell of WinForms (C#)中换行不带空格或换行符的长文本?

代码语言:javascript
复制
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if ((e.ColumnIndex == 1) && (e.FormattedValue != null))
    {
        SizeF sizeGraph = e.Graphics.MeasureString(e.FormattedValue.ToString(), e.CellStyle.Font, e.CellBounds.Width);

        RectangleF cellBounds = e.CellBounds;
        cellBounds.Height = cellBounds.Height;

        if (e.CellBounds.Height > sizeGraph.Height)
        {
            cellBounds.Y += (e.CellBounds.Height - sizeGraph.Height) / 2;
        }
        else
        {
            cellBounds.Y += paddingValue;
        }
        e.PaintBackground(e.ClipBounds, true);

        using (SolidBrush sb = new SolidBrush(e.CellStyle.ForeColor))
        {
            e.Graphics.DrawString(e.FormattedValue.ToString(), e.CellStyle.Font, sb, cellBounds);
        }
        e.Handled = true;
    }
}

在上面的代码中,当索引为1的列的列宽改变时,它会扭曲文本,但不会增加每行的高度。

EN

回答 1

Stack Overflow用户

发布于 2012-01-23 01:21:38

我不认为有一种方法可以使用格式化标志将单个单词包装成多行。

你可能需要通过计算自己去做。

一个示例(未针对速度进行优化):

代码语言:javascript
复制
private void PaintCell(Graphics g, Rectangle cellBounds, string longWord) {
  g.TextRenderingHint = TextRenderingHint.AntiAlias;
  float wordLength = 0;
  StringBuilder sb = new StringBuilder();
  List<string> words = new List<string>();

  foreach (char c in longWord) {
    float charWidth = g.MeasureString(c.ToString(), SystemFonts.DefaultFont,
                                      Point.Empty, StringFormat.GenericTypographic).Width;
    if (sb.Length > 0 && wordLength + charWidth > cellBounds.Width) {
      words.Add(sb.ToString());
      sb = new StringBuilder();
      wordLength = 0;
    }
    wordLength += charWidth;
    sb.Append(c);
  }

  if (sb.Length > 0)
    words.Add(sb.ToString());

  g.TextRenderingHint = TextRenderingHint.SystemDefault;
  g.DrawString(string.Join(Environment.NewLine, words.ToArray()),
               SystemFonts.DefaultFont,
               Brushes.Black,
               cellBounds,
               StringFormat.GenericTypographic);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8922505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档