As for the issue, Windows Forms is event driven, so any code you want executed generally starts with an event handler. In the case of what you have, that's a handler for the Click
event of a Button
. The user clicks a Button
, the Button
raises its Click
event, the form handles that event and executes the specified code. It's up you to decide when you want your code executed and what event will be raised at that time. You haven't told us anything about that so we can't really help with specifics. You have two examples in that code already though. The form raises its Load
event when the form loads, so you can handle that event and execute code at that time. The KeyPress
event of a TextBox
is raised when the user presses a keyboard key while that TextBox
has focus, so you can handle that event and execute code at that time. The form, all its controls and other object that are not controls raise lots of different events, so you need to think about exactly you want to prompt your code to be executed, find the event that is raised at that time and handle it.
Looking at the code, it seems to be validating the contents of a TextBox
, so the obvious choice seems to be the Validating
event of that TextBox
. Make sure that you read the documentation for that event so that you understand exactly how it works. ALWAYS read the relevant documentation for new types and members. You can simply click the name in code and press F1 to navigate directly to the appropriate page, but you should also have the home page favourited/bookmarked in your browser.
Note also that you can call the form's Validate
method to raise the Validating
event on all controls. That's a great way to make sure that even controls that never received focus get validated before the user tries to save data or whatever.