0

我使用绑定到 DataTable 的 DataGridView。DefaultCellStyle.WrapMode 设置为 false,一切都按我想要的方式工作。但是,我想使用一个自定义的 CellPainting(下面的代码),它可以做应该做的事情,但是 WrapMode 不再受到尊重,并且当添加到 DataGridView1 的“URL”列时,现在会包装更长的字符串。

  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 回答