Checking fields in winforms

Is there a shortcut in checking fields in winforms? For example, saving a record requires a specific text block. What I always do is first check all the required fields programmatically before saving. Example:

protected bool CheckFields() { bool isOk = false; if(textBox1.Text != String.Empty) { isOk = true; } return isOk; } private void btnSave_Click(object sender, EventArgs e) { if(CheckFields()) { Save();// Some function to save record. } } 

Is there a countable part of Validator in ASP.Net in winforms? Or in any other way ...

+4
source share
3 answers

Here is one approach:

  private List<Control> m_lstControlsToValidate; private void SetupControlsToValidate() { m_lstControlsToValidate = new List<Control>(); //Add data entry controls to be validated m_lstControlsToValidate.Add(sometextbox); m_lstControlsToValidate.Add(sometextbox2); } private void ValidateSomeTextBox() { //Call this method in validating event. //Validate and set error using error provider } Private void Save() { foreach(Control thisControl in m_lstControlsToValidate) { if(!string.IsNullOrEmpty(ErrorProvider.GetError(thisControl))) { //Do not save, show messagebox. return; } } //Continue save } 

EDIT:

For each control in m_lstControlsToValidate, you need to write a validation method that will be run in the Validating event.

ErrorProvider.GetError (thisControl) will return some errortext or emptystring. An empty line means that the control is in order. In addition, the control contains some error, and we abort the save operation.

We do this on all controls in m_lstControlsToValidate. If all controls are error free, we continue with the cancellation of the cancellation.

+5
source

In fact, in Win Form you should use the Control.Validating event to check when the user is working on the form. But to maintain validation, you have a write code that checks that all data is correctly inserted by the user. For example, you can create a required TextBox and iterate over all form controls that are looking for this type of control and check that the user has entered some text.

0
source

Use a validation control. They are best used.

Moreover,

 protected bool CheckFields() { bool isOk = false; if(textBox1.Text != String.Empty) { isOk = true; } return isOk; } 

May be significantly reduced:

 protected bool CheckFields() { return textBox1.Text != String.Empty; } 
0
source

All Articles