実行時に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
そこでイベントをオーバーライドしてTag
、neoliskの提案に従って、ラベルではなくDrawStringを使用して保存されているテキストを追加しました。
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";