Skip to main content Skip to footer

How to Prevent the AfterEdit Event from Firing Multiple Times

If you want to run a block of code only once in the AfterEdit event, you can use a boolean flag to check if the Del key is pressed using the KeyDown event and then wrap your block of code inside an If condition in the AfterEdit event.

int count = 1;
bool DelPressed = false;

private void Form1_Load(object sender, EventArgs e)
{
    //sample data
    for (int i = 1; i < 5; i++)
    {
        for (int j = 1; j < 5; j++)
        {
            c1FlexGrid1[i, j] = $"{i},{j}";
        }
    }
    c1FlexGrid1.AfterEdit += C1FlexGrid1_AfterEdit;
    c1FlexGrid1.KeyDown += C1FlexGrid1_KeyDown;
}

private void C1FlexGrid1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        DelPressed = true;
    }
}

private void C1FlexGrid1_AfterEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
{
    //write your code which you do not need multiple times in this code block
    if (DelPressed)
    {
        //write your own code
        Console.WriteLine("AfterEdit" + count++);

        DelPressed = false;
    }
}