How can I show the error icon when the user is typing in the cell?
By default when you set ErrorText
for a cell, the error icon will not show when the cell is in edit mode. Also none of events of the DataGridView
handles change of text while the user is typing in a cell.
To set an error text and show error icon while the user is typing in a cell you should follow these steps:
- Get the editing control in
EditingControlShowing
and handle its TextChanged
event.
- In the
TextChanged
event of the text box, set or remove ErrorText
for the cell.
- Apply a right padding to the cell when starting edit and in
CellBeginEdit
event and remove it in CellEndEdit
.
- Paint error icon in
CellPainting
event.

Example
This example shows an error in cell while the user types in the first cell if the text of the cell become empty.
In EditingControlShowing
attach TextChanged
event to the TextBox
:
void grid_EditingControlShowing(object sender,DataGridViewEditingControlShowingEventArgs e)
{
if (this.grid.CurrentCell.ColumnIndex == 0)
{
var textbox = e.Control as DataGridViewTextBoxEditingControl;
if (textbox != null)
{
textbox.TextChanged -= textBox_TextChanged;
textbox.TextChanged += textBox_TextChanged;
}
}
}
In TextChanged
event of TextBox
perform validation and remove or set ErrorText
for the cell:
void textBox_TextChanged(object sender, EventArgs e)
{
var textbox = (TextBox)sender;
if (string.IsNullOrEmpty(textbox.Text))
this.grid.CurrentCell.ErrorText = "Invalid Value";
else
this.grid.CurrentCell.ErrorText = null;
}
In CellBeginEdit
add a right padding to show error Icon and in CellEndEdit
we remove the padding:
void grid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
var cell = grid.Rows[e.RowIndex].Cells[e.ColumnIndex];
cell.Style.Padding = new Padding(0, 0, 18, 0);
}
void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var cell = grid.Rows[e.RowIndex].Cells[e.RowIndex];
cell.Style.Padding = new Padding(0, 0, 0, 0);
}
In CellPainting
draw error icon yourself:
private void grid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.All &
~(DataGridViewPaintParts.ErrorIcon));
if (!String.IsNullOrEmpty(e.ErrorText))
{
GraphicsContainer container = e.Graphics.BeginContainer();
e.Graphics.TranslateTransform(e.CellStyle.Padding.Right, 0);
e.Paint(e.CellBounds, DataGridViewPaintParts.ErrorIcon);
e.Graphics.EndContainer(container);
}
e.Handled = true;
}