Best option for control validation C# Windows Forms

Pat Hanks 141 Reputation points
2022-12-08T14:05:43.007+00:00

I am looking for the best option for a C# Windows Form app to validate the controls have all been completed. This form has the tab control with a couple tabs, which has the controls I am wanting to use validation on.

268641-settingsform.gif

I looked at using the errorProvider, but ran into an issue to cancel the form. Once the errorprovider was triggered you can not close the form until the validation is successful. The Cancel button nor the X will close the form. I do like the way it provides the icon and text rather than a messagebox however I need to allow the user to cancel if they are unable to complete the form. I have tried several things I have found while googling like setting CausesValidation to false for the cancel button and a couple other.

Also, I would like to have the Save button disabled until the controls have been modified, then trigger the button to be enabled.

If I can't find a clean way to do this, I will have to use a method to be called from the close button prior to closing the form.

Developer technologies Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-12-09T06:11:48.64+00:00

    @Pat Hanks , Welcome to Microsoft Q&A, based on your description, I make a code example and I reproduced your problem.

    I recommend that we need to avoid using the code e.Cancel=true; then you could close the form without the limit of errorprovider control.

    Here is a code example you could refer to.

    private void textBox1_Validating(object sender, CancelEventArgs e)  
            {  
                if(string.IsNullOrEmpty(textBox1.Text))  
                {  
                    //e.Cancel=true;  
                    errorProvider1.SetError(textBox1, "please enter");  
      
                }  
                  
            }  
    

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.