jasonline
jasonline

Reputation: 9054

Validating a DataGridView in C#

I have a parent form with one DataGridView and a button. When the button is clicked, it opens a child window and when closed, goes back to the parent form. I want to validate the value being inputted in a cell of the DAtaGridView. I'm using CellValidated event and showing a message box whenever it inputs an invalid value. However, when I click on the button to open the child window and close it back, the DataGridView becomes just a white box with a diagonal cross, and a NullReferenceException shows.

Does anyone know what causes this issue? If not, what's the best way to validate a value of the cell and which event to put it in?

Upvotes: 0

Views: 1804

Answers (2)

Gabriel GM
Gabriel GM

Reputation: 6649

Whenever validating a cell in a DataGridView, you should use the CellValidating event.

You can get the data using the DataGridViewCellValidatingEventArgs and set the Cancel property to True if it is invalid data. This is gonna prevent the CellValidated event from being raised and should give the focus back to the given cell.

If this doesn't help, can you provide some code and show us where the exception occured?

Upvotes: 0

Uranus
Uranus

Reputation: 1690

Just setup Visual Studio as described in this article: How to: Break When an Exception is Thrown. This way, you will be able to catch this exception in the debugger, and see where its roots are.

Upvotes: 0

Related Questions