Hi I have a windows form containing a menu bar, tool strip and a DataGridView control. I am using VB.Net.
I have a save button on the tool strip and a save menu item. I need validation to run before save occurs. My problem is that if a cells value is changed and then either of the save buttons is clicked, validation does not run and so the new value is not saved.
I have had a look at the events on the DataGridView such as the 'leave' event however none seem to do what I want. I.e. 'leave' does not run when either of the save buttons is clicked.
Does anyone know of a way I can run my validation code when one of these buttons is clicked (or any other button).
Any help is greatly appreciated!
The issue is that clicking on either a button on a ToolStrip
control or an item on a MenuStrip
control does not cause the Validating
/Validate
events to be raised by the currently selected control. This is by-design. Interacting with menus and toolbars does not cause the currently selected control to lose focus, which means that validation is never triggered.
If you think about it carefully, this even makes sense. Imagine that your validation logic required each cell to contain a value (i.e., it prevented cells from being left blank or empty). If the validation event was triggered each time that a user tried to select an item from a menu or toolbar, they couldn't even "Paste" anything into the cell!
You'll have to add a bunch of ugly, additional logic to your form if you insist on overriding this behavior, and you run the risk of seriously annoying your user. Suffice it to say that I don't recommend it.
The better solution is to extract your validation logic into a separate method, and call it manually at the beginning of the event handler method for each menu/toolstrip item that you want to trigger validation. Alternatively, you could raise the LostFocus
event for your DataGridView
control at the beginning of your Save toolstrip button click event handler using the InvokeLostFocus
method. Something like:
InvokeLostFocus(myDataGridView, EventArgs.Empty)
For me, calling my Form's "Validate" function from within the menu's click event was enough to do what I needed, which included forcing the grid's validation events to fire.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With