如何向 DataGridView 单元格添加标签

Nia*_*all 5 c# datagridview winforms

有没有什么方法可以在运行时向 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;
}
Run Code Online (Sandbox Code Playgroud)

谁能解释我现在如何“附加”labelcell

编辑2 - 解决方案我无法完全按照上述方式工作,因此最终对 DataGridViewColumn 和 Cell 进行子类化,并重写那里的事件,以根据 neolisk 的建议使用 DrawString 而不是 LabelPaint添加存储在其中的任何文本: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();
    }
}
Run Code Online (Sandbox Code Playgroud)

实施为:

DataGridViewLabelCellColumn col = new DataGridViewLabelCellColumn();
dgv.Columns.Add(col);
col.HeaderText = "Header";
col.Name = "Name"; 
Run Code Online (Sandbox Code Playgroud)

Neo*_*isk 1

如果您正在进行自定义绘画,则应该使用Graphics.DrawString而不是Label控件。你的e类型是DataGridViewCellPaintingEventArgs,所以它有Graphics属性。这是使用PaintEventArgs的示例,您的应该类似。