January 20, 2021
Hot Topics:

Working with the DataGridView Control

  • By Bipin Joshi
  • Send Email »
  • More Articles »

To perform any custom validation on the cell or row being edited, you can use the CellValidating and RowValidation events, respectively. If you want to validate the data cell by cell, the former event is useful where you want to validate the data for the entire row at once then the later event is handy. In your example, you use the CellValidating event, as shown below:

private void dataGridView1_CellValidating(object sender,
   DataGridViewCellValidatingEventArgs e)
   if (dataGridView1.Columns[e.ColumnIndex].Name == "Column1")
      if (e.FormattedValue.ToString().Length < 5)
            ErrorText = "Customer ID must be at least 5
                         characters long!";

Here, you want to ensure that the length of the new CustomerID is at least five characters. You do this by using the FormattedValue property of the DataGridViewCellValidatingEventArgs parameter. This property returns the new value entered in the cell. If it is less than five characters, you set the ErrorText property of that cell to some error message. Notice how the ColumnIndex and RowIndex properties of DataGridViewCellValidatingEventArgs parameter are used. At run time, if the validation fails, the DataGridView displays a red exclamation icon in that cell (see below). Hovering the mouse pointer on the icon displays the ErrorText that you set earlier.

Click here for a larger image.


The DataGridView control of Windows Forms is a versatile control that can help you create professional-looking data entry forms. It not only supports data binding but also provides frequently needed column types, such as combo box and button. The DataGridView event model is really extensive and one can take control of validation and entry by using many of these events. Although you used DataSet as the source of your data, you also could have used generic collections if required.

Download the Code

You can download the code that accompanies the article here.

About the Author

Bipin Joshi is the proprietor of BinaryIntellect Consulting, where he conducts premier training programs on .NET technologies. He wears many hats, including software consultant, mentor, prolific author, webmaster, Microsoft MVP, and member of ASPInsiders. Having adopted the Yoga way of life, Bipin also teaches Kriya Yoga to interested individuals. His detailed profile can be read on his blog. He also can be reached there.

Page 5 of 5

This article was originally published on December 28, 2007

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date