简体   繁体   中英

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?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM