I have extended the DataGridView cell to display the text from its Tag property in the corner (e.g. displaying the day number in the corner of a calendar) and would like to be able to specify the Color and opacity of the text.
To accomplish this I have added 2 properties to the subclassed DataGridView cell, however they are not storing their values at runtime. This is the DataGridViewCell and Column:
class DataGridViewLabelCell : DataGridViewTextBoxCell
{
private Color _textColor;
private int _opacity;
public Color TextColor { get { return _textColor; } set { _textColor = value; } }
public int Opacity { get { return _opacity; } set { _opacity = value; } }
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// Call the base class method to paint the default cell appearance.
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts);
if (base.Tag != null)
{
string tag = base.Tag.ToString();
Point point = new Point(base.ContentBounds.Location.X, base.ContentBounds.Location.Y);
Font font = new Font("Arial", 25.0F, FontStyle.Bold);
graphics.DrawString(tag, font, new SolidBrush(Color.FromArgb(_opacity, _textColor)), cellBounds.X, cellBounds.Y);
}
}
}
public class DataGridViewLabelCellColumn : DataGridViewColumn
{
public DataGridViewLabelCellColumn(Color TextColor, int Opacity = 128)
{
DataGridViewLabelCell template = new DataGridViewLabelCell();
template.TextColor = TextColor;
template.Opacity = Opacity;
this.CellTemplate = template;
}
}
I add the columns as follows:
col = new DataGridViewLabelCellColumn(Color.Blue, 115);
dgv.Columns.Add(col);
col.HeaderText = "Saturday";
col.Name = "Saturday";
However, if I add a breakpoint to the graphics.DrawString line neither _textColor nor _opacity have a value. If I assign them default values as follows:
private Color _textColor = Color.Red;
private int _opacity = 128;
Then it works fine. How can I ensure that the values get stored in the CellTemplate?
I believe it’s because the
CellTemplateis stored as a more genericDataGridViewCell, rather than the subclassedLabelCell. At any rate, storing the values on the Column and just referencing them from there works fine: