Вы находитесь на странице: 1из 2

Figure 7-5: DataGridView object 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

2. CellEnter: Current Cell

3. CellFormatting: Current Cell

4. CellClick: Current Cell

5. CellMouseClick: Current Cell

6. CellFormatting: Current Cell

7. CellBeginEdit: Current Cell

8. CellFormatting: Current Cell

9. EditingControlShowing: Current Cell

10. CellDirtyStateChanged (to dirty): A character was typed into Current Cell

11. CellMouseLeave: Current Cell

12. CellMouseEnter: Next Cell

13. CellFormatting: Next Cell

14. CellMouseDown: Next Cell

15. CellLeave: Current Cell

16. CellValidating: Current Cell

17. CellParsing: Current Cell

18.

19.
16.

17.

18. CellValueChanged: Current Cell

19. CellDirtyStateChanged (to clear): Current Cell

20. CellValidated: Current Cell

21. CellFormatting: Current Cell

22. CellStateChanged (to None): Current Cell

23. CellStateChanged (to Selected): Next Cell

24. CellEndEdit: Current Cell

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)
{

Debug.WriteLine("Cell Validating: "


+ e.RowIndex.ToString() + ","+e.ColumnIndex.ToString());
//Check to see if last name has at least 1 character
if (e.ColumnIndex==1 //Last Name
&& e.FormattedValue.ToString().Trim().Length==0)
{
e.Cancel = true;
}
}

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.

Вам также может понравиться