Madonna Remon
Madonna Remon

Reputation: 1219

DataGridView How to Validate&Select cell

I have a grid view contains multiple columns and I adjusted their input type to be double.

When the user selects a cell, enters its data, I want to check if it matches the type of double.

If the user clicks on another cell and the one he is about to leave doesn't match and it failed in parsing, I want the focus return to the failed cell, and not moving to the new selected one, to force the user to enter a valid data before continuing filling the rest of the cells.

The problem is that it always leaves the failed cell. Even when I used other functions like validating or validated.

Here is my code sample:

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
        {

            var selectedCell = dataGridView1.SelectedCells[0];
            if (selectedCell.OwningColumn.ValueType == typeof(double))
            {
                try
                {
                    double result = Convert.ToDouble(selectedCell.EditedFormattedValue.ToString());
                    if (result <= 0)
                    {
                        MessageBox.Show("Please Positive Numbers Only");
                        dataGridView1.Focus();
                        dataGridView1.CurrentCell = dataGridView1.Rows[selectedCell.RowIndex].Cells[selectedCell.ColumnIndex];
                        dataGridView1.BeginEdit(true);
                    }
                    else
                    {
                        dataGridView1.CurrentCell.Value = result;
                    }
                }
                catch
                {
                    MessageBox.Show("Please Enter Numbers Only");
                } 
            }
        }

Upvotes: 1

Views: 1180

Answers (1)

Krzysztof Lach
Krzysztof Lach

Reputation: 1380

You can use event DataGridView.CellValidating. This should fix your problem.

Example:

   private void dataGridView1_CellValidating(object sender, 
                                           DataGridViewCellValidatingEventArgs e)
    {
        if (e.ColumnIndex == 1) // 1 should be your column index
        {
            int i;

            if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
            {
                e.Cancel = true;
                label1.Text ="please enter numeric";
            }
            else
            {
                // the input is numeric 
            }
        }
    }

DataGridView.CellValidating Event

How to: Validate Data in the Windows Forms DataGridView Control

CellValueChanged vs CellValidating Events for DataGridView

Upvotes: 2

Related Questions