Home
Manage Your Code
Snippet: Validation using errorprovider (C#)
Title: Validation using errorprovider Language: C#
Description: Validating the input on a textbox using the errorprovider. Views: 549
Author: Snorre Gartland Date Added: 10/3/2007
Copy Code  
1/// <summary>
2        /// Validates the input of a textbox. Test on no input and length of the input string defined as a parameter maxLength.
3        /// </summary>
4        /// <param name="myTextBox">The name of the textbox.</param>
5        /// <param name="myErrorProvider">The name of the errorprovider.</param>
6        /// <param name="maxLength">Max length of the input.</param>
7        /// <returns>True if valid.</returns>
8        private static bool ValidInput(Control myTextBox, ErrorProvider myErrorProvider, int maxLength) 
9        {
10            bool status = true;
11            if (myTextBox.Text == "")
12            {
13                myErrorProvider.SetError(myTextBox, "No input detected. Please fill in.");
14                status = false;
15            }
16            else {
17                if (myTextBox.Text.Length > 0 && myTextBox.Text.Length <= maxLength)
18                {
19                    myErrorProvider.SetError(myTextBox, "");
20                }
21                else {
22                    myErrorProvider.SetError(myTextBox, string.Format("Please check the length of the input. Max length is {0}.", maxLength));
23                    status = false;
24                }
25            }
26            return status;
27        } //private static bool ValidInput
Usage
//Default names used on controls
if (ValidInput(textBox1, errorProvider1, 11))
{
//do something
}
Notes
Need to add a errorprovider to the form.