0
votes

I have a DataGridView attached to an XML DataSource. Everytime user edits a cell the program automatically updates the relative XML file. To handle editing I am using both:

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
       //do edit
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
       //do edit
}

Editing works like that, user clicks on a cell and changes the value. Then he should press the Enter key to make everything work fine, but for example if he click the mouse button outside or if he goes outside the cell with the left arrow key, the program messes up. It works anyway because I managed to handle this exception but I would like my program to handle this situation better. For example, when user enters a cell I want to deny him to go on other cells with the Arrow Keys. I tried to catch the KeyDown event but it didn't work:

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if ((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right)) //etc...
        {
            e.Handled = true;
        }
    }

Basically when begin edit starts I want to edit the cell ONLY if user presses Enter. Any ideas? If the control (in this case the cell) looses focus during the edit (user presses Esc, clicks the mouse outside of the control, etc...) I need to prevent the EndEdit event from starting.

2

2 Answers

2
votes

You can use RowValidating Event to cancel event and RowValidated event for to save like this:

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        string data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        if(!ValidateData(data))
            e.Cancel = true;
    }

    private bool ValidateData(string data)
    {
        // do validation which u want to do.
    }

    private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        string data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        SaveData(data);
    }

    private void SaveData(string data)
    {
        // save data
    }
1
votes

Rather use the RowValidating event that allows you to cancel the action in cases of invalid data.