有没有什么方法可以在运行时向 DataGridView 单元格插入标签 - 例如我想在每个单元格的顶角有一个红色的小数字?我是否需要创建一个新的 DataGridViewColumn 类型,或者我是否可以在填充 DataGridView 时只在其中添加一个标签?
编辑 我现在正尝试按照 Neolisk 的建议使用 Cell painting 来执行此操作,但我不确定如何实际显示标签。我有以下代码,在设置其 Value
之前,我现在将标签文本添加为单元格的 Tag
:
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 子类化并覆盖那里的 Paint
事件根据 neolisk 的建议,使用 DrawString 而不是 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";
最佳答案
如果你正在做自定义绘画,你应该使用 Graphics.DrawString而不是 Label
控件。您的 e
属于 DataGridViewCellPaintingEventArgs
类型,因此它具有 Graphics
属性。这是使用 PaintEventArgs 的示例,你的应该是相似的。
关于c# - 如何将标签添加到 DataGridView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014781/