Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

Developers, How to use validations in windows form c# application.. as like we using in Asp.net (req field validation,compare validation, etc.)

user-image
Question ajoutée par Mohamed Shameer , OpenText ECM Consultant & ECM Administrator , Petrochemical Industrial Company
Date de publication: 2014/05/13
Mohamed Yousif
par Mohamed Yousif , .Net developer , Free Lancer

you have to do it manually like this :

if(textbox1.text == "")

{

   MessageBox.show("SomeThing....");

return;

}

 

and there is some controls in Devexpress you can use it to add some visual appearance like highlighting the control

Murad AlShawakfa
par Murad AlShawakfa , Sitecore Consultant , Embrace home loans

Well if you are considering minimizing the hassle you can always use the MaskedTextBox control, you can add your own validation rules to it, so that it fits your need, if anything else it should be event driven

OnTextChanged, OnClick, .. etc.

Vladimir Bojovic
par Vladimir Bojovic , Solution Architect, SDM , Ericsson

There are two levels of validation one might want to implement.

 

1) Field level

Validation should control what characters are valid as input to the field, and what would be the overal structure of the input (examples: xx-xx-xxxx, xx.xx.xx.xx). This can be maintained either through MaskedTextBox, or it can be manualy implemented by responding to regular TextBox field events.

For instance, events KeyPress, KeyUp or KeyDown can be used to validate current input key value against list of valid values (including control keys), or if you are making custom masked field, you can use this for string assembly of final text that would be presented.

This example limits the input of a textBox to digits only:

 

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);

        }

 

Event (Focus)Leave can be used instead of KeyUp/Down if you wan't to check validity of input after user has completed the field and attempted to leave it.

This example warns user of constraints for field being leaved:

 

private void textBox1_Leave(object sender, EventArgs e)

        {

            if (textBox1.Text.Length ==0)

                MessageBox.Show("Field shouldn't be empty!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

 

2) Form level

Validation of completion of mandatory fields and additional validation against a list of values for specific field. Validation against a list of values might be implemented to prevent duplicated entries in the database, or as replacement for ComboBox with finite list of values.

This validation should be triggered after pressing the OK button on the form.

 

 

 

More Questions Like This