0

私は、DataTable にバインドされている DataGridView を使用しています。DefaultCellStyle.WrapMode は false に設定されており、すべてが思いどおりに機能しています。しかし、私はカスタム CellPainting (以下のコード) を使用したいと考えています。

  private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
   { 
       if (e.RowIndex < 0) return;

       if (e.ColumnIndex == dataGridView1.Columns["URL"].Index)
       {
           if ((e.State & DataGridViewElementStates.Selected) ==
              DataGridViewElementStates.Selected)
               return;
           e.CellStyle.WrapMode = DataGridViewTriState.False;
           Rectangle rect = new Rectangle(e.CellBounds.X, e.CellBounds.Y,
                                          e.CellBounds.Width - 1, e.CellBounds.Height - 1);

           using (System.Drawing.Drawing2D.LinearGradientBrush lgb =
             new System.Drawing.Drawing2D.LinearGradientBrush(rect, Color.White, Color.Honeydew, 0f))
           {
               e.Graphics.FillRectangle(lgb, rect);
           }

           if (e.Value == null) return;

           using (System.Drawing.Pen pen = new System.Drawing.Pen(dataGridView1.GridColor))
           {
               e.Graphics.DrawRectangle(pen, e.CellBounds.X - 1, e.CellBounds.Y - 1,
                 e.CellBounds.Width, e.CellBounds.Height);
           }

           StringFormat sf = new StringFormat();
           sf.LineAlignment = StringAlignment.Center;
           sf.Alignment = StringAlignment.Near;

           using (System.Drawing.Brush valueBrush = new SolidBrush(e.CellStyle.ForeColor))
           {
               e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, valueBrush, rect, sf);

           }

           e.Handled = true;
       }

     }

次の行を追加しようとしました:

dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.False;

それは動作しません、私は試しました

e.CellStyle.WrapMode = DataGridViewTriState.False;

どちらも機能しません。

カスタム CellPainting を使用しDefaultCellStyle.WrapModeて false に設定するにはどうすればよいですか?

4

1 に答える 1

1

e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, valueBrush, rect, sf);使用しようとする代わりにTextRenderer

var textFormatFlag = TextFormatFlags.SingleLine | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;
TextRenderer.DrawText(e.Graphics, e.Value.ToString(), e.CellStyle.Font, rect, e.CellStyle.ForeColor, textFormatFlag);

セルのコンテンツがセルよりも広い場合は、次のフラグも追加します。

TextFormatFlags.EndEllipsis

「...」で終了します:)

利用可能なオプションの詳細については、こちらをご覧ください。

于 2013-02-07T07:49:10.113 に答える