有没有办法在运行时将标签插入 DataGridView 单元格 - 例如,我想在每个单元格的顶角有一个红色的小数字?我是否需要创建一个新的 DataGridViewColumn 类型,或者我可以在填充 DataGridView 时在那里添加一个标签?
编辑我现在正尝试按照 Neolisk 的建议使用细胞绘画来做到这一点,但我不确定如何实际显示要显示的标签。我有以下代码,现在我将标签文本添加为单元格Tag
,然后再设置Value
:
private void dgvMonthView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dgv = this.dgvMonthView;
DataGridViewCell cell = dgv[e.ColumnIndex, e.RowIndex];
Label label = new Label();
label.Text = cell.Tag.ToString();
label.Font = new Font("Arial", 5);
label.ForeColor = System.Drawing.Color.Red;
}
谁能解释我现在如何“附加”label
到cell
?
编辑 2 - 解决方案我无法完全按照上述方式工作,因此最终将 DataGridViewColumn 和 Cell 子类化并覆盖那里的事件以使用 DrawString 而不是按照 Neolisk 的建议Paint
添加 Label 存储的任何文本:Tag
class DataGridViewLabelCell : DataGridViewTextBoxCell
{
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);
graphics.DrawString(tag, new Font("Arial", 7.0F), new SolidBrush(Color.Red), cellBounds.X + cellBounds.Width - 15, cellBounds.Y);
}
}
}
public class DataGridViewLabelCellColumn : DataGridViewColumn
{
public DataGridViewLabelCellColumn()
{
this.CellTemplate = new DataGridViewLabelCell();
}
}
实现为:
DataGridViewLabelCellColumn col = new DataGridViewLabelCellColumn();
dgv.Columns.Add(col);
col.HeaderText = "Header";
col.Name = "Name";