C# – How to set focus on specific cell in datagridview after a validation error

cdatagridviewsetfocuswinforms

Friends, I've windows application where I'm using a datagridview to display existing data as well add/edit data. The datagridview has a feature that on Tab/Enter key press the focus will move to next cell. If it's the last column in a row, then the focus will go to the first column of next row. Now after entering data for a cell and pressing Tab/Enter key, if there is an error message for wrongly entered data (like numeric value is not properly formatted or value is less than zero etc. etc.), after showing the error message in a message box, the focus is moving to the next cell. Is there any way that if there is an error message for a particular cell then the focus will be set to that error generating cell only, it'll not move to next cell? In dgView_CellEndEdit event I've tried to select the cell by using the code:

    dgView.Rows[e.RowIndex].Cells["ColumnName"].Value = "0.00";
    dgView.Select();
    dgView.CurrentCell.Selected = true;

But it's not working. In dgView_SelectionChanged event I've used:

    dgView.CurrentCell = dgView[RequiredColumnIndex, RequiredRowIndex];
    dgView.BeginEdit(true);

This also is of no help. Please help me to solve the problem.

Best Answer

I think you should use the CellValidating event for your checks and validation. In case some of the checks fail you could prompt the error message and set e.Handlede.Cancel= false. This will keep the focus in the current error cell until you make the required corrections.

Related Topic