简体   繁体   English

在C#中验证DataGridView

[英]Validating a DataGridView in C#

I have a parent form with one DataGridView and a button. 我有一个带一个DataGridView和一个按钮的父窗体。 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. 我想验证在DAtaGridView单元格中输入的值。 I'm using CellValidated event and showing a message box whenever it inputs an invalid value. 我正在使用CellValidated事件,并在输入无效值时显示一个消息框。 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. 但是,当我单击按钮打开子窗口并将其关闭时,DataGridView变成只是一个带有对角线十字的白框,并显示NullReferenceException。

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 . 只需按照本文中所述安装Visual Studio: 如何:抛出异常时中断 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 . 每当验证DataGridView的单元格时,都应使用CellValidating事件

You can get the data using the DataGridViewCellValidatingEventArgs and set the Cancel property to True if it is invalid data. 您可以使用DataGridViewCellValidatingEventArgs获取数据,如果数据无效,则将Cancel属性设置为True This is gonna prevent the CellValidated event from being raised and should give the focus back to the given cell. 这将防止CellValidated event ,并将焦点重新赋予给定的单元格。

If this doesn't help, can you provide some code and show us where the exception occured? 如果这样做没有帮助,您能否提供一些代码并向我们显示发生异常的位置?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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