1

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;
                    }
                }
        }
}
Lukas Bystricky
  • 1,222
  • 6
  • 16
  • 34
  • can you share your codes? – spajce Jan 25 '13 at 20:23
  • It's a pretty standard CellValidating function, I'll post it above. – Lukas Bystricky Jan 25 '13 at 20:27
  • You get a CellValidating callback when you enter a row ia the GUI, but you are NOT getting a CellValidating callback when you create a new row. Is that the problem you are experiencing or am I missing something? – bas Jan 25 '13 at 20:33
  • 1
    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. But since you are putting in rows/cells programmatically anyway, you could also wonder if you need to rely on the validation mechanism. you could also just "validate" the things you want to validate before you add them to your datagrid. just a thought tho. – bas Jan 25 '13 at 20:39
  • @Haxx: Using BeginEdit and EndEdit seems to work well. Thanks. – Lukas Bystricky Jan 25 '13 at 20:49

1 Answers1

2

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.

bas
  • 13,550
  • 20
  • 69
  • 146