I have implemented a CellPainting event handler that uses TextRenderer.DrawText and it has worked great up until a cell had an ampersand in it. The cell shows the ampersand correctly while editing the cell, but when editing is done and it is drawn, it shows up as a small line (not an underscore).

using System;
using System.Drawing;
using System.Windows.Forms;
namespace StackOverFlowFormExample {
public partial class DataGridViewImplementation : DataGridView {
public DataGridViewImplementation() {
InitializeComponent();
this.ColumnCount = 1;
this.CellPainting += DGV_CellPainting;
}
private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
if (!e.Handled && e.RowIndex > -1 && e.Value != null) {
e.PaintBackground(e.CellBounds, false);
TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
e.CellStyle.Font, e.CellBounds,
e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);
e.Handled = true;
}
}
}
}
//creating the datagridview
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
DataGridViewImplementation dgvi = new DataGridViewImplementation();
this.Controls.Add(dgvi);
dgvi.Rows.Add("this is a & value");
}
}
replacing
TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
e.CellStyle.Font, e.CellBounds,
e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);
with
e.PaintContent(e.ClipBounds);
shows it correctly, of course I want to be able to customize the painting of the content though. I've also tried using
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds);

but it doesn't draw it the same as
e.Paint(e.ClipBounds, e.PaintParts);
I use e.Paint in my actual code when a cell is being painted that doesn't need my customized painting.
How can I get e.Graphics.DrawString to look the same as e.Paint or get TextRenderer.DrawText to display the ampersand correctly?
You want to use the TextRenderer version since DrawString should really only be used for printing:
TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor,
TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter);
The NoPrefix flag will show the ampersand correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With