Introduction
Handling a 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.
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);
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.
private void validateTextDouble(object sender, EventArgs e)
{
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);
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.
private void validateTextCharacter(object sender, EventArgs e)
{
TextBox T = (TextBox)sender;
try
{
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);
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).
private void validateTextIntegerCustomized(object sender, EventArgs e)
{
Exception X = new Exception();
TextBox T = (TextBox)sender;
try
{
int x = int.Parse(T.Text);
if (x <= 0)
throw X;
}
catch (Exception)
{
try
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
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.
private void validateTextDoubleCustomized(object sender, EventArgs e)
{
Exception X = new Exception();
TextBox T = (TextBox)sender;
try
{
double x = double.Parse(T.Text);
if (x < 0 || T.Text.Contains(','))
throw X;
}
catch (Exception)
{
try
{
int CursorIndex = T.SelectionStart - 1;
T.Text = T.Text.Remove(CursorIndex, 1);
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 '#'.
private void validateTextCharacterCustomized(object sender, EventArgs e)
{
TextBox T = (TextBox)sender;
try
{
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);
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 Textbox
es where each one of these Textbox
es uses one of the 6 functions discussed in this article.
History
1.0 (5 July 2011)
Thank you for reading... I hope that this article would at least help anyone who is interested in this issue. If it did this, it would make me so happy :)
Don't take this article as the last solution! Try searching for regular expressions and masked Textbox
es, maybe they will suit you better than this one.
Feel free to give me your comments on the code.