View Single Post
  #2 (permalink)  
Old April 9th, 2005, 10:39 PM
Bob Bedell Bob Bedell is offline
Friend of Wrox
 
Join Date: Jun 2003
Location: , , USA.
Posts: 1,093
Thanks: 1
Thanked 12 Times in 11 Posts
Default

Hi Adbul,

The following will give the user immediate validation feedback when they tab out of an unbound textbox.

1. Create a form with a textbox and a button (the button's only purpose will be to provide a control to receive focus when you tab out of the textbox). Drop an ErrorProvider control on the form to place it in the components tray. Name the ErrorProvider control 'err'.

2. Create a class to store your range criteria as static properties. Here's the code:

Code:
using System;

namespace RangeValidation
{
    public class Globals
    {
        public static int MinRange{get{return 6;}}
        public static int MaxRange{get{return 12;}}

    }
}
3. In the form's InitializeComponent method, find the code that initializes the textbox. Add the following line of code to wire up the Validating event):

Code:
// 
// txtRange
// 
this.txtRange.Validating += new System.ComponentModel.CancelEventHandler(this.RangeValidate);
Notice that the event handler calls the RangeValidate method.

4. Here's the RangeValidate method:

Code:
private void RangeValidate(object sender, CancelEventArgs e)
        {
            Debug.Assert(sender == txtRange, 
                "RangeValidate method called by wrong control");

            try
            {
                int range = int.Parse(txtRange.Text);
                if(range < Globals.MinRange || range > Globals.MaxRange)
                {
                    err.SetError(txtRange, "Range must be between 6 and 12");
                    e.Cancel = true;
                }
            }
            catch
            {
                err.SetError(txtRange, "BUG: Range must be an integer");
                e.Cancel = true;
            }

            if(e.Cancel)
                txtRange.SelectAll();
            else
                err.SetError(txtRange, "");
        }


Include the System.Diagnostics namspace as a using directive.

HTH,

Bob

Reply With Quote