tags:

views:

47

answers:

3

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 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 counter part of Validator in ASP.Net in winforms? Or any other way around...

A: 

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.

Vash
+1  A: 

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.

Aseem Gautam
if(!string.IsNullOrEmpty(ErrorProvider.GetError(thisControl))) { //Do not save, show messagebox. return; }I don't understand the code.. can you please explain..
yonan2236
I have explained under edit.
Aseem Gautam
thanks sir..... :)
yonan2236
A: 

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;
} 
Tom Gullen