0

using c# win forms

i have a form that has many text boxes and combo boxes

some of this controls - not all of them - can not be empty

if the user click on save button i want the labels of that empty controls turns to red ....

i tried

if (cmbNyaba.SelectedIndex == -1)
        {
            lblNyaba.ForeColor = Color.Red;
            return;
        }
        else
        {
            lblNyaba.ForeColor = Color.Black;
        }


if (txtCaseHasr.Text == "")
        {
            lblHasrNum.ForeColor = Color.Red;
            return;
        }
        else
        {
            lblHasrNum.ForeColor = Color.Black;
        }


if (txtCaseNum.Text == "")
        {
            lblCaseNum.ForeColor = Color.Red;
            return;
        }
        else
        {
            lblCaseNum.ForeColor = Color.Black;
        }

but i think its not a good way

should i use tag property or what ?

thanks


i tried

public static Boolean ValidateControle(Control MyObjet, int oblig = 0)
    {
        ErrorProvider err = new ErrorProvider();

        String mess = "";
        Boolean valid = true;
        if (MyObjet != null)
        {

            if (oblig == 1)
            {

                mess = "Can not be empty !";
            }

            if (MyObjet.Text.Trim().Length == 0) valid = false;

            if (MyObjet is ComboBox)
            {
                ComboBox cmb = (MyObjet as ComboBox);
                if (cmb.SelectedIndex == -1)
                {
                    mess = "Select at least one element !";
                    valid = false;
                }
            }
            if (valid == false)
            {
                err.SetError(MyObjet, mess);
                MyObjet.BackColor = Color.FromArgb(253, 108, 119);
            }
            else
            {                   
                err.SetError(MyObjet, "");
                MyObjet.BackColor = Color.White;
            }

            err.SetIconAlignment(MyObjet, ErrorIconAlignment.MiddleRight);
        }    
        return valid;          
    }


private void btnSave_Click(object sender, EventArgs e)
    {


        if (cmbCaseCrime.SelectedIndex == -1 || 
           cmbMember.SelectedIndex == -1 ||
           cmbCaseType.SelectedIndex == -1 ||
           string.IsNullOrEmpty(txtCaseNum.Text) ||
           string.IsNullOrEmpty(txtCaseHasr.Text))
        {
            ValidateControle(cmbCaseCrime, 1);
            ValidateControle(cmbMember, 1);
            ValidateControle(cmbCaseType, 1);
            ValidateControle(txtCaseHasr, 1);
            ValidateControle(txtCaseNum, 1);

            return;
        }

        string str = btnSave.Text;
        switch (str)
        {
            case "add":

                DataTable dt = new DataTable();
                dt = cs.Verify_CASES(txtCaseNum.Text, txtCaseYear.Text, Convert.ToInt32(cmbCaseType.SelectedValue), Convert.ToInt32(cmbCaseRegion.SelectedValue));
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("already added ", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    ce.ADD_CASE(txtCaseNum.Text, txtCaseHasr.Text, dtp_CaseComingDate.Value, txtCaseYear.Text,
                            Convert.ToInt32(cmbCaseType.SelectedValue),
                            Convert.ToInt32(cmbCaseRegion.SelectedValue),
                            Convert.ToInt32(cmbCaseStatus.SelectedValue),
                            Convert.ToInt32(cmbCaseCrime.SelectedValue),
                            Convert.ToInt32(cmbMember.SelectedValue), txtCaseStatusDate.Text);



                    MessageBox.Show("added successfuly", " ", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.txtidCase.Text = ce.GET_LAST_CASE_ID().Rows[0][0].ToString();

                    this.btnAddRemain.Enabled = true;
                    this.cmbCaseRemain.Focus();
                    this.btnSave.Enabled = false;


                }
John Deck
  • 787
  • 1
  • 12
  • 27
  • You have some useful facilities in windows forms to perform validation and show error messages including: • `IDataErrorInfo` Interface • `Validating` Event of Controls • `ErrorProvider` Component `ValidateChildren` Method and `AutoValidate`Property of Form. You may find this post helpful [Validating user input / Give .NET controls status OK or NOK](http://stackoverflow.com/a/35993185/3110834) – Reza Aghaei May 01 '16 at 09:24

4 Answers4

1

First you maust declare the ErrorProvider as global under form class and add a void ClearError as :

     public partial class Form1 : Form
        {
            ErrorProvider err = new ErrorProvider();

            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {

            }
  private void ClearError()       
        {

           // ErrorProvider err = new ErrorProvider();

            foreach (Control cn in this.Controls)
            {

                err.SetError(cn,"");

                err.Clear();
                cn.BackColor = Color.White;

            }
        }

And you must change your btnSave_Click as :

private void btnSave_Click(object sender, EventArgs e)
{

        bool test =true ;
    ClearError (); // for clear all mark error in all conrols in the form
     test=   ValidateControle(cmbCaseCrime, 1);
      test=  ValidateControle(cmbMember, 1);
      test=  ValidateControle(cmbCaseType, 1);
       test= ValidateControle(txtCaseHasr, 1);
      test=  ValidateControle(txtCaseNum, 1);

        if (test ==false )
        {
            MessageBox .Show("You have some error !");
        return;
        }

    string str = btnSave.Text;
    switch (str)
    {
        case "add":

            DataTable dt = new DataTable();
            dt = cs.Verify_CASES(txtCaseNum.Text, txtCaseYear.Text, Convert.ToInt32(cmbCaseType.SelectedValue), Convert.ToInt32(cmbCaseRegion.SelectedValue));
            if (dt.Rows.Count > 0)
            {
                MessageBox.Show("already added ", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                ce.ADD_CASE(txtCaseNum.Text, txtCaseHasr.Text, dtp_CaseComingDate.Value, txtCaseYear.Text,
                        Convert.ToInt32(cmbCaseType.SelectedValue),
                        Convert.ToInt32(cmbCaseRegion.SelectedValue),
                        Convert.ToInt32(cmbCaseStatus.SelectedValue),
                        Convert.ToInt32(cmbCaseCrime.SelectedValue),
                        Convert.ToInt32(cmbMember.SelectedValue), txtCaseStatusDate.Text);



                MessageBox.Show("added successfuly", " ", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.txtidCase.Text = ce.GET_LAST_CASE_ID().Rows[0][0].ToString();

                this.btnAddRemain.Enabled = true;
                this.cmbCaseRemain.Focus();
                this.btnSave.Enabled = false;


            }

I hope that fix your issue, and please vote up the answer and mark it as solved.

Beldi Anouar
  • 2,170
  • 1
  • 12
  • 17
0

The first thing you can do is to find all controls of a given type using this.Controls.OfType<T>. For example, finding which labels are empty could look like

var labels = this.Controls.OfType<Label>();
foreach(var label in labels)
if(label.Text == "")
//the actions you want to do.

In case you have some container controls, though, you'll have to also iterate through them.

The second approach you can try is using the Validating and Validated events.

h8red
  • 713
  • 4
  • 17
0

You can use this function :

    public static Boolean ValidateControle(Control MyObjet, int oblig=0)
    {
        ErrorProvider err=new ErrorProvider ();

        String mess = "";
        Boolean valid = true;
        if (MyObjet != null)
        {

            if (oblig == 1)
            {

                mess = "Can not be empty !";
            }

            if (MyObjet.Text.Trim().Length == 0) valid = false;


            if (MyObjet is ComboBox)
            {
                ComboBox cmb = (MyObjet as ComboBox);
                if (cmb.SelectedIndex == -1)
                {
                    mess = "Select at least one element !";
                    valid = false;
                }
            }


            if (valid == false)
            {
                err.SetError(MyObjet, mess);
                MyObjet.BackColor = Color.FromArgb(253, 108, 119);

            }
            else
            {
                err.SetError(MyObjet, "");
                MyObjet.BackColor = Color.White;
            }

            err.SetIconAlignment(MyObjet, ErrorIconAlignment.BottomRight);
        }
        return valid;
    }

And you can use the oblig parametre to specify if control can be empty. In this call you can specefy witch controls are mandatorys with passing 1 in second parameter Call function by :

 ValidateControle(textBox1, 1);

   ValidateControle(comboBox1,1);
     ValidateControle(comboBox2,0);

Or :

 foreach ( Control cn in this.Controls )
            {
                ValidateControle(cn);

            }
Beldi Anouar
  • 2,170
  • 1
  • 12
  • 17
  • one more question .... where i can use the second part of code ? the first part works well .. put the code continue working and saving the record .. i want to stop saving when empty controls were found – John Deck May 01 '16 at 11:39
  • it worked .... but if i fill one of controls and tried again the error sign still there ... and the other signs did not blinking – John Deck May 01 '16 at 12:03
0

For that you must declare your provider in the class like:

 public partial class Form1 : Form

{
    ErrorProvider err = new ErrorProvider();

    public Form1()
    {
        InitializeComponent();
    }

For testing you must reccord or not you can do:

 private void button3_Click(object sender, EventArgs e)
        {
           bool test  =true  ;

            test= ValidateControle(textBox1, 1);

           test= ValidateControle(comboBox1,1);

           if (test)
           {
               //continue working and saving the record
           }
           else
           {
               //Stop and traancate recording

           }

        }

For clear all error sign you can declare a void as :

private void ClearError()       
        {

            foreach (Control cn in this.Controls)
            {

                err.SetError(cn,"");

                err.Clear();
                cn.BackColor = Color.White;

            }
        }

you can call this function if you want clear error sign. Please if my answers are helpful for you vote up and mark it solved

Beldi Anouar
  • 2,170
  • 1
  • 12
  • 17
  • when the user fill one of the empty text boxes .. it's back color turned white again .. but the sign still there beside all controls including the filled one .. i want to clear it .. and keep the other signs .. i tried to call the function but it didn't work .. – John Deck May 01 '16 at 15:31