Search code examples
c#eventsdatagridviewselectionselectionchanged

Is it possible to let only a user selection trigger a SelectionChanged event on a DataGridView?


SelectionChanged methods are triggered when the selection is changed by program. So, for example, calling dataGridView.ClearSelection() or dataGridView.Rows[0].Selected = true would call the method

private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
}

Is it possible to execute code only when the user changed the selection, e.g. by selecting a row/cell with the mouse or keyboard?


Solution

  • You will have to code this in

    private bool _programmaticChange;
    
    private void SomeMethod()
    {
        _programmaticChange = true;
        dataGridView.ClearSelection();
        _programmaticChange = false;
    }
    
    
    private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        if (_programmaticChange) return;
        // some code
    }
    

    this will make it run only on user actions