Search code examples
asp.netwinformsvalidationerrorprovider

Validation in different Tabs of windows form using ErrorProviders


I am working on a windows Forms Application and trying to validate few textboxes using errorproviders but the problem is when I am clicking on a button present in Tab 1, all the textboxes even present on a different tabs gets validated. I want the validation to occur for textboxes present on the current tab and not on any control present on any other tab. How can I achieve this? Please help. Below is the code related to validation in the click event.

   private void btnCreateUser_Click(object sender, EventArgs e)
    {
          if (this.ValidateChildren(ValidationConstraints.Enabled))
        {
               // Some Code here
        }
    }

Below is code used for validating and validated event for one textbox. I am using similar code for other textboxes as well present on other tabs.

      private void txtFirstNm_Validating(object sender, CancelEventArgs e)
    {
        bool cancel = false;
        if (txtFirstNm.Text.Trim().Length == 0)
        {
            cancel = true;
            errorProvider1.SetError(txtFirstNm,"Please enter First Name");
        }
        else
        {
            cancel = false;
            errorProvider1.SetError(txtFirstNm, "");
        }
        e.Cancel = cancel;
    }

    private void txtFirstNm_Validated(object sender, EventArgs e)
    {
        errorProvider1.SetError(txtFirstNm,"");
    }

Solution

  • The Scenario that is given in my question can be handled by using below code. We can use the ValidationConstraint as Visible and this will make sure that Validation occurs on the Current visible Controls.

      private void btnCreateUser_Click(object sender, EventArgs e)
      {
          if (this.ValidateChildren(ValidationConstraints.Visible))
          {
               // Some Code here
          }
      }