Datagrid View Cell Events
Datagrid View Cell Events
Event Sequence
Here are the events that take place when a cell is entered (the Current Cell) and edited, and then another
cell is clicked (the Next Cell).
1. CellStateChanged (to Selected): Current Cell
10. CellDirtyStateChanged (to dirty): A character was typed into Current Cell
18.
19.
16.
17.
Now that you have a table of the cell events (Table 7-1) and the preceding sequential list of events, you can
code the necessary event handlers to customize the DataGridView object. For example, if you want to keep
a user from changing from one cell to another when the user does not enter an appropriate value into the
first cell, you can set the Cancel property to true in the CellValidating event handler, as shown in the
following code snippet.
Visual Basic
Private Sub EmployeesDataGridView_CellValidating(_
ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) _
Handles EmployeesDataGridView.CellValidating
Debug.WriteLine("Cell Validating: " _
+ e.RowIndex.ToString() + ", " + e.ColumnIndex.ToString())
'Check Last Name to see if last name has at least 1 character
If (e.ColumnIndex = 1 _
And e.FormattedValue.ToString().Trim().Length = 0) Then
e.Cancel = True
End If
End Sub
C#
private void employeesDataGridView_CellValidating(
object sender, DataGridViewCellValidatingEventArgs e)
{
When the code is run and the user attempts to change the last name to an empty string or a string that
consists of spaces, the Cancel property will be set to true and the user will not be allowed to leave the cell.
1.