如何在DataGridViewTextBoxCell of WinForms (C#)中换行不带空格或换行符的长文本?
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的列的列宽改变时,它会扭曲文本,但不会增加每行的高度。
发布于 2012-01-23 01:21:38
我不认为有一种方法可以使用格式化标志将单个单词包装成多行。
你可能需要通过计算自己去做。
一个示例(未针对速度进行优化):
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);
}https://stackoverflow.com/questions/8922505
复制相似问题