DataGridView Data Entry Validation

I faced this issue a couple of times. How to efectively validate data entry inside a DataGridView.  Well, after doing some research and a bit of trial and error, found out a couple of approaches. 

Immediate validation:  For those of you who have used dynamic regular expression validator in c#.  This method is pretty similar.  It checks on the fly the data enter by the user.   Msdn has a nice article on how to implemented. 

http://msdn2.microsoft.com/en-us/library/7ehy30d4(VS.80).aspx

LateValidation: This validation is performed after the user is done entering data.  For the specific project i was working in, it was the perfect choice. However, one has to evaluate the pros and cons of each one.

If you are going to perform complex and multiple validation, you should try the second approach. Also this approach allows the user more flexibility. Lets say the user its not required to enter data in all the rows of the datagridview, the latter approach would work just fine.

On the other hand, if the user is required to enter data in all the rows and the validation is simple; the first approach is convenient.  

In order to implement Immediate validation, the event CellValidation must be handled

Ex

 private void dataGridView1_CellValidating(object sender,
  DataGridViewCellValidatingEventArgs e)
  {
  // Validate the CompanyName entry by disallowing empty strings.
  if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
  {
  if (String.IsNullOrEmpty(e.FormattedValue.ToString())  &&
  dataGridView1[e.ColumnIndex,e.RowIndex].IsInEditMode )
  {
  dataGridView1.Rows[e.RowIndex].ErrorText =
  "Company Name must not be empty";
       //e.Cancel = true;


  }
  }
  }

The validation to check if the cell is in edit mode is very important. Keep that in mind.

For the Late Validation, there must be an event that is perform once the user finish entering data.  In the implementation of this event,  we would have to go through all the rows that have any info on them and perform the validation required, setting the appropiate error messages in the cell.ErrorMessage property.

 Ex

foreach(DataGridViewRow mRow in datagrid.Rows)
{

if (!Double.TryParse(mRow.Cells["Lots of amount"].FormattedValue.ToString(), out result))

{

mRow.Cells["Lots of amount"].ErrorText = "Please enter a valid number";

//flag to indicate there is an error

error = true;

}

}

~ by ajhorus on July 4, 2007.

7 Responses to “DataGridView Data Entry Validation”

  1. The problem is finding a decent event to perform the Late Validation on.

    Which DataGridView event do you use?

  2. In our specific case scenario, we had a submit button that triggered all the validation. I am guessing you want to use an event like the CurrentDataRow change, or something along those lines.

  3. Have you found a way to validate the cell as it is being typed? Currently the CellValidate triggers only after you leave a cell. I would like to validate the information as it is being entered… such as making sure it only accepts integers and immediately looking up the value against a database (such as a part number) and retrieving the information from the DB to populate the rest of the row.

  4. Hello Steve, There is actually a way to implement this you’ll have to register the editingControlShowing. Once this event is registered you can then register any event you like to the editing control.

    private void monitorDataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
    mKeyUpController.Clear();
    Control ctl = e.Control;
    //monitorDataGrid.CurrentCell.ErrorText = String.Empty;
    DataGridViewTextBoxEditingControl dText = (DataGridViewTextBoxEditingControl)ctl;
    dText.EditingControlDataGridView.EditMode = DataGridViewEditMode.EditOnEnter;
    dText.KeyDown -= new KeyEventHandler(dText_KeyDown);
    dText.KeyUp -= new KeyEventHandler(dText_KeyUp);
    dText.KeyDown += new KeyEventHandler(dText_KeyDown);
    dText.KeyUp += new KeyEventHandler(dText_KeyUp);
    }

  5. CurrentCellDirtyStateChanged is also a good one that happens as the user types into the cell.

  6. Hi There,
    I’m almost crying here, i was halfway through writing a custom control (since thats what I had to do in c/mfc) due to the pathetic lack of controls(ala msflexgrid) when I found this entry.
    i had started learning C# by writing a point of sale system (head office and branch etc etc) and just assumed C#’s controls were shit as well, since c/c++ cells/rows were not abstracted to classes and therefor not fireing ANY usefull events. i had to use arrays of textboxes, which while barely serving the purpose was actually quite pathetic(one should not have to be reduced to such behavior) Bla bla anyway i found this article and it looks like I’ll be able to use this control, which although not perfect, is a VAST improvement on past tech (except maybe Borland which had decent stuff, although it worked with firebird/interbase). People just don’t know how lucky they are these days. Thanks OP.

    Also, I’ll post here when I’m finshed with the normalisation and
    masterfiles and have any q’s.

  7. how can i enter data from datagrid into the data base.

Leave a comment