biff biff - 7 months ago 69
C# Question

Show Placeholder Text in DataGridView Cells

I need to show a placeholder which contains a string in first two coloumns of the first row of datagrid view in winforms. The placeholder is to be displayed when the datagrid is empty.

enter image description here


You need to handle CellPainting event and draw place holder yourself:

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    if (e.RowIndex < 0 || e.ColumnIndex < 0)        /*If a header cell*/
    if (!(e.ColumnIndex == 0 || e.ColumnIndex == 1) /*If not our desired columns*/

    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;