我需要显示一个占位符,该占位符在Winforms的datagrid视图的第一行的前两列中包含一个字符串。当数据网格为空时,将显示占位符。
最佳答案
您需要处理CellPainting
事件并自己绘制占位符:
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0) /*If a header cell*/
return;
if (!(e.ColumnIndex == 0 || e.ColumnIndex == 1) /*If not our desired columns*/
return;
if(e.Value == null || e.Value == DBNull.Value) /*If value is null*/
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All
& ~(DataGridViewPaintParts.ContentForeground));
TextRenderer.DrawText(e.Graphics, "Enter a value", e.CellStyle.Font,
e.CellBounds, SystemColors.GrayText, TextFormatFlags.Left);
e.Handled = true;
}
}