Articles Languages C# How To
Article
Browse
Code
Stats
Revisions
(6)
Alternati
ves
Commen
ts (31)
F+skdCOGRQx6m
10C1FD69
Numbers and Characters only Textbox
Validation in C# !
Tagged
as
C#
Beginner
Related
Articles
Mahmoud Hesham El-Magdoub, 5 Jul 2011 CPOL
4.75 (23 votes)
Ready to
use custom
textbox
with
1
validation
properties 4.75/5 - 23 votes
2 removed
TextBox 4.58, 1.30 [?]
a
whith
Validation
Functions
Rate this:
and
MaskEdit
Vote!
vote 1vote 2vote 3vote 4vote 5
Filter your Textbox to Integers, Characters or doubles only in C# , Create
TextBox customized numeric alphabetic texboxes
with
Download sample - 10.63 KB
Validation
Functions
Download source code - 41.78 KB
and
MaskEdit
Introduction
Learn
Regular
Expressions
(RegEx) Handling a
with Ease
Xtended
TextBox
Textbox exception is a very common task and found in nearly every
GUI. Usually the handling of a Textbox is the process of permitting the user to
write only numbers (whether integers or real) or alphabetical characters. All the
code I've found on the net tackles this issue with regular expressions, it works
well but has some limitations. In this article, I do the Textbox exception
handling in a different, easy and flexible way.
Using the Code
The way of doing this is quite simple and straight forward. I mainly work on the
"TextChanged" action of the TextBox. There are three main types of functions I
used for the "TextChanged" action and they are:
validateTextInteger()
validateTextDouble()
validateTextCharacter()
The validateTextInteger() function permits the user to only type positive or
negative Integer values, the validateTextDouble() function permits the user to
write positive or negative double values only and finally the
validateTextCharacter() function only allows the user to write alphabetical
characters.
To use any of these functions, the user simply selects a Textbox then goes to
the actions panel and on the "TextChanged" row, he selects one of these three
functions according to the exception handling he desires.
These three functions are normal validation functions, to make them more
flexible I made another three customized functions and they will be discussed in
detail in the Customized Validations section.
ValidateTextInteger
I parse the text to an integer and if all is ok, nothing will be changed but if the
parsing function throws an exception, I catch it and remove the new character
that made this exception then I rearrange the textbox cursor back to its place. I
check the text and if it's equal to the minus sign I leave it as it is because the
parsing function would throw an exception if the text is only a minus sign.
Hide Copy Code
private void validateTextInteger(object sender, EventArgs e)
{
Exception X = new Exception();
TextBox T = (TextBox)sender;
try
{
if (T.Text != "-")
{
int x = int.Parse(T.Text);
}
}
catch (Exception)
{
try
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
catch (Exception) { }
}
}
Examples
When Pressed
After Handling
11.
11
34a5
345
5_67
567
ValidateTextDouble
I parse the text to a double and if all is ok, nothing will be changed but the
parsing function throws an exception. I catch it and remove the new character
that made this exception then I rearrange the Textbox cursor back to its place.
I check the text and if it's equal to the minus sign, I leave it as it is because the
parsing function would throw an exception if the text is only a minus sign. I also
check if the text contains a comma ',' and throw an exception if found because
the parsing function does not see the comma as an exception.
Hide Shrink
private void validateTextDouble(object sender, EventArgs e)
{
Copy Code
Exception X = new Exception();
TextBox T = (TextBox)sender;
try
{
if (T.Text != "-")
{
double x = double.Parse(T.Text);
if (T.Text.Contains(','))
throw X;
}
}
catch (Exception)
{
try
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
catch (Exception) { }
}
}
Examples:
When Pressed
After Handling
23.97.
23.97
0d.01
0.01
2$16
216
ValidateTextCharacter
I use the textContainsUnallowedCharacter() function to check if this new text
contains a number or not, if it does not contain then nothing will be changed
but if it contains a number I remove the new character (number) that made this
exception then I rearrange the textbox cursor back to its place.
Hide Shrink
private void validateTextCharacter(object sender, EventArgs e)
{
TextBox T = (TextBox)sender;
try
{
//Not Allowing Numbers
char[] UnallowedCharacters = { '0', '1',
Copy Code
'2',
'4',
'6',
'8',
'3',
'5',
'7',
'9'};
if (textContainsUnallowedCharacter(T.Text,UnallowedCharacters))
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
}
catch(Exception){ }
}
private bool textContainsUnallowedCharacter(string T, char[] UnallowedCharacters)
{
for (int i = 0; i < UnallowedCharacters.Length; i++)
if (T.Contains(UnallowedCharacters[i]))
return true;
return false;
}
Examples:
When Pressed
After Handling
ab6cd
abcd
8tyhg
tyhg
%$#@6
%$#@
Customized Validations
Other than these validations, I made some extra validations to make these
functions more flexible, such as only permitting the user to enter positive
integer values and disallowing the user to enter some specific characters. These
functions are:
ValidateInetegerCustomized
This function is the same as validateTextInteger() but I add the customizing
(filtering) condition which is 'if (x <= 0)', this only permits the user to write
Integers from 1 to (2^31 -1).
Hide Shrink
private void validateTextIntegerCustomized(object sender, EventArgs e)
Copy Code
{
Exception X = new Exception();
TextBox T = (TextBox)sender;
try
{
int x = int.Parse(T.Text);
//Customizing Condition
if (x <= 0)
throw X;
}
catch (Exception)
{
try
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
catch (Exception) { }
}
}
Note: You can change this condition to 'if ( x < 0)' which will only permit the
user to write Integers from 0 to (2^31 -1).
ValidateDoubleCustomized
This function is the same as validateTextDouble() but I add the customizing
(filtering) condition which is 'if (x < 0)', this only permits the user to write
positive double values.
Hide Shrink
private void validateTextDoubleCustomized(object sender, EventArgs e)
{
Exception X = new Exception();
TextBox T = (TextBox)sender;
try
{
double x = double.Parse(T.Text);
//Customizing Condition (Only numbers larger than or
//equal to zero are permitted)
if (x < 0 || T.Text.Contains(','))
throw X;
}
catch (Exception)
{
Copy Code
try
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
catch (Exception) { }
}
}
Note: You can change this condition to 'if ( x <= 0)' which will only permit the
user to write positive double values starting from 1.
ValidateCharacterCustomized
This function is the same as validateTextCharacter() but here I change the
values of the UnallowedCharacters array to not only disallow numbers but to
also disallow the Underscore '_' and the Hash '#'.
Hide Copy Code
private void validateTextCharacterCustomized(object sender, EventArgs e)
{
TextBox T = (TextBox)sender;
try
{
//Not Allowing Numbers, Underscore or Hash
char[] UnallowedCharacters = { '0', '1',
'2', '3',
'4', '5',
'6', '7',
'8', '9','_','#'};
if (textContainsUnallowedCharacter(T.Text, UnallowedCharacters))
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
//Align Cursor to same index
T.SelectionStart = CursorIndex;
T.SelectionLength = 0;
}
}
catch (Exception) { }
}
Note: You can change the values of this array to disallow the user to write any
character you want.
GUI
The GUI is simple and is only used for illustration, it has 6 Textboxes where
each one of these Textboxes uses one of the 6 functions discussed in this
article.
History