Click here to Skip to main content
Licence CPOL
First Posted 9 Nov 2008
Views 35,330
Downloads 1,059
Bookmarked 56 times

Simple Numeric TextBox

By DaveyM69 | 9 Nov 2008
A WinForms TextBox that only accepts digits.

1
1 vote, 4.0%
2
3 votes, 12.0%
3
4 votes, 16.0%
4
17 votes, 68.0%
5
4.87/5 - 25 votes
4 removed
μ 4.58, σa 1.55 [?]

Overview

This is a simple extension/restriction of the System.Windows.Forms.TextBox component. Only digits can be entered into the control. Pasting is also checked, and if the text contains other characters, then it is cancelled. I found many examples on various websites, but none that I found were suitable for my purpose. Either they allowed or enforced things I didn't want (see 'What I haven't done' below), or they didn't completely handle all the standard keyboard and mouse functions (see 'Surely this is simple' below), for example, allowing the Home key or Shift+End etc.

Language

The source code is in C#, .NET 2.0, VS2008. I've included the compiled DLL so VB users can use this control.

What I haven't done

I haven't added any range or bounds control - it's a text box, not an int/double/decimal... box. There is no support for number separators, currency symbols, or even the - sign. They weren't required for the implementation I needed. If you want to add them, it shouldn't be too difficult.

Surely this is simple, you just...

That's what I thought too, until about two minutes into coding this! There's actually quite a lot that we do all the time with the text box, but never give it a second thought. As well as digits, we need to allow edit key combinations and navigation/selection keys and combinations. Pasting can be done either by keyboard or by mouse actions, so handling key events for this isn't sufficient.

The code

The interesting parts of the code are in the overridden OnKeyDown and the private CheckPasteValid methods.

OnKeyDown

I've simply built bools for numeric, edit, and navigation keys so I can test one value for each group. Ctrl+A sometimes needs separate handling, so I created one for that too.

protected override void OnKeyDown(KeyEventArgs e)
{
    bool result = true;

    bool numericKeys = (
        ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
        (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9))
        && e.Modifiers != Keys.Shift);

    bool ctrlA = e.KeyCode == Keys.A && e.Modifiers == Keys.Control;

    bool editKeys = (
        (e.KeyCode == Keys.Z && e.Modifiers == Keys.Control) ||
        (e.KeyCode == Keys.X && e.Modifiers == Keys.Control) ||
        (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) ||
        (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) ||
        e.KeyCode == Keys.Delete ||
        e.KeyCode == Keys.Back);

    bool navigationKeys = (
        e.KeyCode == Keys.Up ||
        e.KeyCode == Keys.Right ||
        e.KeyCode == Keys.Down ||
        e.KeyCode == Keys.Left ||
        e.KeyCode == Keys.Home ||
        e.KeyCode == Keys.End);

    if (!(numericKeys || editKeys || navigationKeys))
    {
        if (ctrlA)
        // Do select all as OS/Framework
        // does not always seem to implement this.
            SelectAll();
        result = false;
    }
    if (!result) // If not valid key then suppress and handle.
    {
        e.SuppressKeyPress = true;
        e.Handled = true;
        if (ctrlA) { } // Do Nothing!
        else
            OnKeyRejected(new KeyRejectedEventArgs(e.KeyCode));
    }
    else
        base.OnKeyDown(e);
}

CheckPasteValid

When a paste message is received, it's caught in the overridden WndProc, which then calls this method. Based on the result, if necessary, it returns without calling the base's WndProc, therefore cancelling the message. The code for CheckPasteValid is given below. After setting the default values, we attempt to get the text from the clipboard. If there's an error or there's no valid text, then an appropriate reject reason is set and we return. If OK, we then build a string from the current text and the clipboard's text. The final step is to check if the clipboard's text contains any non digit characters and set the required reject reason.

private PasteEventArgs CheckPasteValid()
{
    // Default values.
    PasteRejectReasons rejectReason = PasteRejectReasons.Accepted;
    string originalText = Text;
    string clipboardText = string.Empty;
    string textResult = string.Empty;

    try
    {
        clipboardText = Clipboard.GetText(TextDataFormat.Text);
        if (clipboardText.Length > 0) // Does clipboard contain text?
        {
            // Store text value as it will be post paste assuming it is valid.
            textResult = (
                Text.Remove(SelectionStart, 
                SelectionLength).Insert(SelectionStart, clipboardText));
            foreach (char c in clipboardText) // Check for any non digit characters.
            {
                if (!char.IsDigit(c))
                {
                    rejectReason = PasteRejectReasons.InvalidCharacter;
                    break;
                }
            }
        }
        else
            rejectReason = PasteRejectReasons.NoData;
    }
    catch
    {
        rejectReason = PasteRejectReasons.Unknown;
    }
    return new PasteEventArgs(originalText, clipboardText, textResult, rejectReason);
}

New stuff

Events

  • KeyRejected - Occurs when a KeyDown event is suppressed.
  • PasteRejected - Occurs when a Paste attempt is disallowed.

Properties

  • DefaultText - The string to use when there is no value (cannot be null or empty).

Nested classes

There are two nested event argument classes.

KeyRejectedEventArgs

An instance of this is created every time a key down is suppressed. It has just one property:

  • Key - They rejected key (System.Windows.Forms.Keys).

PasteEventArgs

An instance of this is created every time a Paste message is received. It's used internally, but its primary purpose is as the event args in the PasteRejected event. It has four properties:

  • OriginalText - The text as it was before the paste (or still is, if rejected).
  • ClipboardText - The text that is attempting to paste.
  • TextResult - The text that is or would have been the result of the paste.
  • RejectReason - An enum (PasteRejectReasons) that indicates the reason for rejection if rejected, or PasteRejectReasons.Accepted for internal use if the paste is OK.

History

  • 7 November 2008: Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DaveyM69



United Kingdom United Kingdom

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberTHines014:24 3 Dec '11  
NewsAn another silent TextBox to accept number for a range. [modified] PinmemberManish K. Agarwal2:16 27 Sep '11  
GeneralRe: An another silent TextBox to accept number for a range. PinmentorDaveyM697:47 28 Sep '11  
GeneralMy vote of 5 PinmemberNaerling11:12 4 May '11  
GeneralMy vote of 5 PinmemberDufresne16:13 11 Jan '11  
Generalhowto add a decimal PinmemberMember 197457018:04 22 Oct '09  
GeneralRe: howto add a decimal PinmvpDaveyM6911:45 23 Oct '09  
QuestionConfused PinmemberXmen W.K.7:23 2 Apr '09  
AnswerRe: Confused PinmvpDaveyM697:29 2 Apr '09  
GeneralRe: Confused PinmemberXmen W.K.16:43 2 Apr '09  
Generalvery kool PinmemberDonsw12:33 7 Feb '09  
GeneralRe: very kool PinmvpDaveyM692:21 8 Feb '09  
GeneralVery simple NumericTextBox for example Pinmember-=SerP=-21:41 10 Nov '08  
class NumericTextBox : TextBox
{
    const int ES_NUMBER = 0x2000; 
    const int WM_PASTE = 0x0302; 
    const string NumberTemplate = @"^\d+$";
 
    protected override CreateParams CreateParams
    {
        get 
	{ 
		CreateParams parameters = base.CreateParams; 
		parameters.Style |= ES_NUMBER; 
		return parameters; 
	}
    }
 
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_PASTE)
        {
            string data = Clipboard.GetDataObject().GetData(DataFormats.Text) as string; 
            if (!Regex.IsMatch(data, NumberTemplate)) 
		return;
        } 
        base.WndProc(ref m);
    }
}

GeneralRe: Very simple NumericTextBox for example [modified] PinmemberDaveyM692:08 11 Nov '08  
GeneralRe: Very simple NumericTextBox for example Pinmember-Dy22:58 7 Jun '09  
General[Message Deleted] Pinmembernicorac21:40 10 Nov '08  
GeneralRe: Testing all the accepted keys PinmemberDaveyM692:38 11 Nov '08  
GeneralRe: Testing all the accepted keys Pinmembernicorac5:45 11 Nov '08  
GeneralRe: Testing all the accepted keys PinmemberDaveyM6912:45 11 Nov '08  
QuestionCan be simpler PinmemberJacques Bourgeois10:07 10 Nov '08  
AnswerRe: Can be simpler PinmemberDaveyM6916:33 10 Nov '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120210.1 | Last Updated 9 Nov 2008
Article Copyright 2008 by DaveyM69
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid