2

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

在此处输入图像描述

4

3 回答 3

5

您需要自己处理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;
    }
}
于 2016-11-03T09:42:49.593 回答
0

因此,您可以改进此(为 工作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...";
}

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

于 2016-11-03T09:30:48.023 回答
0

只是想分享我对@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;
    }
}
于 2021-03-29T03:01:37.527 回答