Im in my first C# and GUI class and im wondering how i stop an event from executing. In my case i have a button and a textbox, if the button is clicked when there is invalid input in the textbox the button event should stop executing.
Loading
Im in my first C# and GUI class and im wondering how i stop an event from executing. In my case i have a button and a textbox, if the button is clicked when there is invalid input in the textbox the button event should stop executing.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Naimish MakwanaRank #324 · 7.7K reputationPosted Feb 8, 2023, 11:06 PM EST
Hello David,
You can use the
returnstatement to stop the execution of the event handler method.Example:
private void Button_Click(object sender, EventArgs e) { string name = txtName.Text; if (!Validate(name)) { MessageBox.Show("Invalid name!"); return; //From here your execution stop } // Continue processing... }Thanks
Naimish Makwana
Vishal JoshiRank #377 · 6.7K reputationPosted Feb 9, 2023, 12:59 AM EST
Hello
Please try the below way to complete the requirement.
In properties choose “Events” and under focus double-click on “validating”. after select validation method you need to write method like below code sample:
private void textBoxName_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrWhiteSpace(textBoxName.Text)) { e.Cancel = true; textBoxName.Focus(); errorProviderApp.SetError(textBoxName, "Name should not be left blank!"); } else { e.Cancel = false; errorProviderApp.SetError(textBoxName, ""); } }Please check below article for more details.
https://www.c-sharpcorner.com/blogs/how-to-use-validation-in-windows-form-application
Thanks
David Oest15 reputationPosted Feb 10, 2023, 11:13 AM EST
Thank you so much for the simple and fast answer.