2012-01-19 8 views
0

WinForms(C#)のDataGridViewTextBoxCellに長いテキストをスペースや改行なしで折り返す方法は?上記のコードでwinforms(C#)のDataGridViewTextBoxCellに長いテキストをスペースや改行なしで折り返す方法はありますか

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を有する列の列幅が変更されたときにテキストをwarppingが、各行の高さを増加されません。

+0

は、誰もがそれを知っているんでしょうか? – user186246

答えて

0

フォーマットフラグを使用して複数の行に1語をラップする方法はありません。

あなたはたぶん計算を自分で行う必要があります。

(速度のために最適化されていない)例:

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); 
} 
関連する問題