The Solution 1 and 2 are good.
I want to add that the
KeyDown
event can be used to prevent entry of other than numbers and decimal but at the same time allow use of keys like
Del, BackSpace
etc.
If it is required to enable pasting only decimal number, then I think the
WndProc
method explained here
WndProc method[
^] is to be handled.
The list of Windows Messages are given here
http://wiki.winehq.org/List_Of_Windows_Messages[
^]
The text to be pasted is combined with the existing text and tested with
Regex
with pattern
"^\d*\.?\d*$"
before being pasted, to see that the entire text contains only digits and one or none decimal.
Since,
WndProc
is a protected method, the
TextBox
is to be sub classed to provide the desired functionality as shown below:
public class DecimalTextBox : TextBox {
protected override void WndProc(ref System.Windows.Forms.Message m)
{
try {
if (m.Msg !=0x302) {
base.WndProc(ref m);
return;
}
string modifiedText = Text + Clipboard.GetText();
if (Regex.IsMatch(modifiedText,@"^\d*\.?\d*$",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)){
Text = modifiedText;
SelectionStart = Text.Length;
}
} catch {
}
}
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs args) {
if (args.Control || args.Alt)
return;
switch(args.KeyCode){
case Keys.End:
case Keys.Home:
case Keys.Left:
case Keys.Right:
case Keys.Back:
case Keys.Delete:
return;
}
if (!char.IsDigit((char)args.KeyData) &&
(args.KeyCode!= Keys.OemPeriod ||
(args.KeyCode == Keys.OemPeriod && Text.Contains(".")))){
args.SuppressKeyPress=true;
}
}
}