ComponentOne FlexGrid for WinForms
Step 3 of 5: Add Custom Mouse and Keyboard Handling
FlexGrid for WinForms Tutorials > Outline Tutorial > Step 3 of 5: Add Custom Mouse and Keyboard Handling

The C1FlexGrid provides the expanding and collapsing for you, but you may extend and customize its behavior. Every time a branch is expanded or collapsed, the control fires the BeforeCollapse and AfterCollapse events so you may take actions in response to that. Furthermore, you may use the Collapsed property to get and set the collapsed state of each branch in code.

In this tutorial, we will trap the DoubleClick and KeyPress events to expand and collapse nodes when the user double clicks or presses the ENTER key. Add the following DoubleClick and KeyPress events to the form:

To write code in Visual Basic

Visual Basic
Copy Code
Private Sub C1FlexGrid1_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles C1FlexGrid1.DoubleClick
    If C1FlexGrid1.MouseCol = 0 Then
        ToggleNodeState()
    End If
End Sub
 
Private Sub C1FlexGrid1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles C1FlexGrid1.KeyPress
    If e.KeyChar = vbCr Then
        ToggleNodeState()
    End If
End Sub
 
Private Sub ToggleNodeState()
 
    ' If the current row is not a node, no work is done.
    Dim r As Row = C1FlexGrid1.Rows(C1FlexGrid1.Row)
    If Not r.IsNode Then Exit Sub
 
    ' Toggle the collapsed state.
    r.Node.Collapsed = Not r.Node.Collapsed
End Sub

To write code in C#

C#
Copy Code
private void c1FlexGrid1_DoubleClick( object sender, EventArgs e)
{
    if ( c1FlexGrid1.MouseCol == 0 ) 
    {
        ToggleNodeState();
    }
}
 
private void c1FlexGrid1_KeyPress( object sender, KeyPressEventArgs e)
{
    if ( e.KeyChar == 13 ) 
    {
        ToggleNodeState();
    }
}
 
private void ToggleNodeState() 
{
 
    // If the current row is not a node, no work is done.
     Row r = c1FlexGrid1.Rows[c1FlexGrid1.Row];
    if (! r.IsNode ) return;
 
    // Toggle the collapsed state.
    r.Node.Collapsed = !r.Node.Collapsed;
}

Run the program and observe the following:

The event handlers check whether the user double-clicked the first column or hit the ENTER key, then call the ToggleNodeState routine. ToggleNodeState checks whether the current row is a node row, and toggles the value of the Collapsed property if it is.

See Also