【发布时间】:2012-12-23 21:19:05
【问题描述】:
有什么方法可以在运行时向 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 子类化并覆盖 Paint 事件以添加存储的任何文本根据neolisk的建议,在Tag中使用DrawString而不是Label:
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";
【问题讨论】:
-
您是否尝试过自定义单元格绘制?您应该能够完成任何类型的自定义绘图,包括角落里的小标签。 See this.
-
谢谢,这听起来可能很理想,但仍不确定如何实际添加标签。我用一个例子更新了我的问题
标签: c# winforms datagridview