Introduction
Recently I had to make a TextBox in Silverlight to restrict the user input such that the textbox:
- Allows only numeric input (0 to 9)
- Restricts all special characters (Except decimal point ".")
- Allows numbers with utmost two decimal places (can be customized through code to accept more digits after decimal)
Background
There are multiple ways of making numeric textboxes, including validators, converters and string formatters, but these will allow the user to type as many numbers as he wants after the decimal point, but will round off the value on losing focus.
The solution given in this article restricts the user from typing beyond 2 digits after decimal point.
Using the code
I have used a Silverlight project with C# as programming language, but the same should hold good with any other version of .NET and programming languages.
Here's how my TextBox
is defined:
<TextBox Width="100" Height="24"
KeyDown="TextBox_KeyDown" />
The KeyDown
event handler is where the validation takes place. The code is as follows:
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
const int KEYCODE_Dot_OnKeyboard = 190;
const int KEYCODE_Dot_OnNumericKeyPad = 110;
if (Keyboard.Modifiers == ModifierKeys.Shift)
{
e.Handled = true;
}
if ((e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 ||
e.PlatformKeyCode == KEYCODE_Dot_OnKeyboard ||
e.PlatformKeyCode == KEYCODE_Dot_OnNumericKeyPad))
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1,
e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) +
strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && (e.PlatformKeyCode ==
KEYCODE_Dot_OnKeyboard ||
e.PlatformKeyCode == KEYCODE_Dot_OnNumericKeyPad))
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Key.A && e.Key <= Key.Z || e.Key == Key.Space)
{
e.Handled = true;
}
}
Points of Interest
Well, it is a simple tip but will be most useful in data entry pages and forms. Hope it helps you all.