Implement handlers for the DataGridView control's CellValidating and CellEndEdit events.

The CellValidating event handler is where you determine whether the value of a cell in the SchoolName column is empty. If the cell value fails validation, set the Cancel property of the System.Windows.Forms.DataGridViewCellValidatingEventArgs class to true. This causes the DataGridView control to prevent the cursor from leaving the cell. Set the ErrorText property on the row to an explanatory string. This displays an error icon with a ToolTip that contains the error text. In the CellEndEdit event handler, set the ErrorText property on the row to the empty string. The CellEndEdit event occurs only when the cell exits edit mode, which it cannot do if it fails validation.

private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
    // Validate the SchoolName entry by disallowing empty strings.
    if (dataGridView1.Columns[e.ColumnIndex].Name == "SchoolName")
        if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
            dataGridView1.Rows[e.RowIndex].ErrorText =
                "Company Name must not be empty";
            e.Cancel = true;

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    // Clear the row error in case the user presses ESC.  
    dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;

And Voila!

Print | posted on Sunday, September 13, 2009 6:53 PM


No comments posted yet.

Your comment:


Copyright © intermark

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski