开发者

Fields validation in winforms

开发者 https://www.devze.com 2023-01-12 23:17 出处:网络
Is there a shortcut in validating fields in winforms? For example a particular textBox is required to be filled up before saving a record. What I always do is I check first all the required fields pro

Is there a shortcut in validating fields in winforms? For example a particular textBox is required to be filled up before saving a record. What I always do is I check first all the required fields programatically before saving. Example:

protected boo开发者_如何转开发l 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 counter part of Validator in ASP.Net in winforms? Or any other way around...


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 the validation method that would be fired in Validating event.

ErrorProvider.GetError(thisControl) will return some errortext or emptystring. Empty string means the control is fine. Else the control contains some error and we abort the save operation.

We do this on all the controls in m_lstControlsToValidate. If all controls are error free we continue with save else abort.


Not really, in Win Form you should use the Control.Validating Event for validation when user is working on the form. But for saving validation You have write code that check that all data are correctly inserted by user. For instance you can create a mandatory TextBox, and iterate over all form controls looking for this type of control and check that user has inputed some text.


Use a validation control. They are the best thing to use.

Also,

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

Can be shorterned considerably to:

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

精彩评论

暂无评论...
验证码 换一张
取 消