简体   繁体   中英

CellValueChanged vs CellValidating Events for DataGridView

What's the best place to implement validation logic code and conditional formatting code for a DataGridView?

In a lot of books and articles that I've read on this control, it seems to suggest that the appropriate event to handle for this is the CellValidating one. Well, the name more than implies this as well.

However, this event triggers a bit too often for my tastes and I'm not sure it is required. For example, this event triggers everytimes the users switches to another row.

On the other hand, the CellValueChanged event seems to trigger only when the value of the cell changes, which means the validation code runs only when the value changes and not everytime a user changes cells.

Now, since so many books use the CellValidating event, I wonder if there is not any gotcha (in display for example) with using the CellValueChanged?

I understand that the impact in performance should be irrelevant when using simple validation and conditional highlighting rules but I would as much prefer it not to run useless code everytime the user moves to another cell if it can be avoided.

Thanks,

I'm using CellValueChanged currently on a grid with custom validation and have had no problems with display or anything else.

I used this event because I wanted to fire off a certain order of events, but only when the user changes the value of a cell.

I have not noticed much in the way of a performance hit (tested with 100 - 5000 rows).

I think in the end it depends on what your validation needs are. In my case, CellValueChanged has done what I wanted/needed.

EDIT

The biggest thing about the CellValidating event is that you can stop the user from leaving a cell, if the value entered does not pass your validation. I didn't want to do this.

Its simple, inside the CellValidatingEvent you need to check if a condition is right. If your condition is false then you just add this code e.cancel . It will prevent the cursor to lost its focus

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