Lukas Bystricky
Lukas Bystricky

Reputation: 1272

Validate DataGridView cells for data read from file

I have an unbounded DataGridView with several columns. I've created a CellValidating function, and it works well. Right now I'm trying to read data in from a text file and put it in the DataGridView. When I do this however, the CellValidating function never gets called. Is it possible to validate data entered like this?

Edit: Here's part of my CellValidate function:

private void Grid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    string headerText = Grid.Columns[e.ColumnIndex].HeaderText;

        switch (headerText)
        {
            case "Number":

                if (!String.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    if (!Regex.IsMatch(e.FormattedValue.ToString(), @"(^\d{1,2}$)"))
                    {
                        MessageBox.Show("Number must be a 1 or 2 digit positive number");
                        e.Cancel = true;
                    }
                }
        }
}

Upvotes: 1

Views: 592

Answers (1)

bas
bas

Reputation: 14982

CellValidating and RowValidating events fire when the current cell/row is being changed or when ending an edit operation. You should be able to force the validation trigger using BeginEdit and EndEdit.

Upvotes: 2

Related Questions