I an using a DataGridView, which is bound to a DataTable. The DefaultCellStyle.WrapMode is set to false and everything is working just the way I want it. However, I want to use a custom CellPainting (code below), which does what is supposed to, but the WrapMode is no longer respected and longer strings are now wrapped when added to the “URL” column of DataGridView1.
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;
}
}
I have tried adding the following line:
dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.False;
it does not work, I have tried
e.CellStyle.WrapMode = DataGridViewTriState.False;
it does not work either.
How do I use the custom CellPainting and set the DefaultCellStyle.WrapMode to false?
Instead of
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, valueBrush, rect, sf);try to useTextRenderer.If content of cell is wider than cell add this flag as well:
to end it with ‘…’ 🙂
For more information what options are available look here.