在 DataGridView 单元格中显示占位符文本

Show Placeholder Text in DataGridView Cells

我需要在 Winforms 数据网格视图第一行的前两列中显示一个包含字符串的占位符。数据网格为空时显示占位符。

因此,您可以改进它(适用于 Textbox)并更改为 dataGrid.Text

Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";

myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);

public void RemoveText(object sender, EventArgs e)
{
     if (myTxtbx.Text == "Enter text here...") {
        myTxtbx.Text = "";
     }
}

public void AddText(object sender, EventArgs e)
{
     if(String.IsNullOrWhiteSpace(myTxtbx.Text))
        myTxtbx.Text = "Enter text here...";
}

注意:myTxtbx.Text = "Enter text here...";if (myTxtbx.Text == "Enter text here...")中的字符串"Enter text here..."必须相等。

您需要自己处理 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;
    }
}

只是想分享我对@Reza Aghaei 惊人回答的看法。它将用斜体字“NULL”替换所有空值,类似于 SQL Server Management Studio 的做法。

private void MainGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0)
        return;

    if (e.Value == null || e.Value == DBNull.Value)
    {
        e.Paint(e.CellBounds, DataGridViewPaintParts.All
                & ~(DataGridViewPaintParts.ContentForeground));

        var font = new Font(e.CellStyle.Font, FontStyle.Italic);
        var color = SystemColors.ActiveCaptionText;
        if (((DataGridView)sender).SelectedCells.Contains(((DataGridView)sender)[e.ColumnIndex, e.RowIndex]))
                color = Color.White;

        TextRenderer.DrawText(e.Graphics, "NULL", font, e.CellBounds, color, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);

        e.Handled = true;
    }
}