Search code examples
c#errorprovider

how validate empty controls in windowsform


i create a windows form with multi controls (text box & date time picker & combo box) then use error provider to check if a control is empty or not (14 of controls must be filled), with a messy code to check (14 if statement on the save button event) it shows the errors but stores the form in database. how can i prevent save button to insert the form whiteout any of this 14 controls

red Square shows controls that needs to be saved


Solution

  • my problem solved by validating event .

    under validating event of each control that need to be filled`

      private void cmb_nof_Validating(object sender, CancelEventArgs e)
        {
           Validatecmb_nof();
        }
        private bool Validatecmb_nof()
        {
    
            bool bstatus = true;
            if (string.IsNullOrEmpty(cmb_nof.Text))
            {
                errorProvider1.SetError(cmb_nof, "item required");
                bstatus = false;
            }
            else
            {
                errorProvider1.SetError(cmb_nof, "");
            }
            return bstatus;
        }
    

    `and under saver button click event this code

                bool Valnof = Validatecmb_nof();
    
                if ( Valnof )
                {       
                //some events   
                  }
    
                else
                {
                    MessageBox.Show("Please enter valid data");
                }