locked
allow only number in textbox RRS feed

  • Question

  • hi .. how do i allow only user to key in number in the textbox..

    when they try to key in character.. they cant..  how i do that

    thanks

    Tuesday, February 19, 2008 1:15 PM

Answers

  • I've mocked up with a custom TextBox control which can only accept numbers from keyboard input, drag and drop and paste command.

    Code Snippet
    using System;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Controls;

    namespace Sheva.Windows.Controls
    {
    public class NumberTextBox : TextBox
    {
    static NumberTextBox()
    {
    EventManager.RegisterClassHandler(
    typeof(NumberTextBox),
    DataObject.PastingEvent,
    (DataObjectPastingEventHandler)((sender, e) =>
    {
    if (!IsDataValid(e.DataObject))
    {
    DataObject data = new DataObject();
    data.SetText(String.Empty);
    e.DataObject = data;
    e.Handled = false;
    }
    }));
    }

    protected override void OnDrop(DragEventArgs e)
    {
    e.Handled = !IsDataValid(e.Data);
    base.OnDrop(e);
    }

    protected override void OnDragOver(DragEventArgs e)
    {
    if (!IsDataValid(e.Data))
    {
    e.Handled = true;
    e.Effects = DragDropEffects.None;
    }

    base.OnDragEnter(e);
    }

    private static Boolean IsDataValid(IDataObject data)
    {
    Boolean isValid = false;
    if (data != null)
    {
    String text = data.GetData(DataFormats.Text) as String;
    if (!String.IsNullOrEmpty(text == null ? null : text.Trim()))
    {
    Int32 result = -1;
    if (Int32.TryParse(text, out result))
    {
    if (result > 0)
    {
    isValid = true;
    }
    }
    }
    }

    return isValid;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
    if (e.Key < Key.D0 || e.Key > Key.D9)
    {
    if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
    {
    if (e.Key != Key.Back)
    {
    e.Handled = true;
    }
    }
    }
    }
    }
    }

    Hope this helps

    Thursday, February 21, 2008 5:08 AM
  • Number only Textbox

    http://dedjo.blogspot.com/2007/11/number-only-textbox.html

     

    or you can try wiring the Text Composition Events like OnPreviewTextInput etc.

     

    Tuesday, February 19, 2008 2:00 PM

All replies

  • Number only Textbox

    http://dedjo.blogspot.com/2007/11/number-only-textbox.html

     

    or you can try wiring the Text Composition Events like OnPreviewTextInput etc.

     

    Tuesday, February 19, 2008 2:00 PM
  • I've mocked up with a custom TextBox control which can only accept numbers from keyboard input, drag and drop and paste command.

    Code Snippet
    using System;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Controls;

    namespace Sheva.Windows.Controls
    {
    public class NumberTextBox : TextBox
    {
    static NumberTextBox()
    {
    EventManager.RegisterClassHandler(
    typeof(NumberTextBox),
    DataObject.PastingEvent,
    (DataObjectPastingEventHandler)((sender, e) =>
    {
    if (!IsDataValid(e.DataObject))
    {
    DataObject data = new DataObject();
    data.SetText(String.Empty);
    e.DataObject = data;
    e.Handled = false;
    }
    }));
    }

    protected override void OnDrop(DragEventArgs e)
    {
    e.Handled = !IsDataValid(e.Data);
    base.OnDrop(e);
    }

    protected override void OnDragOver(DragEventArgs e)
    {
    if (!IsDataValid(e.Data))
    {
    e.Handled = true;
    e.Effects = DragDropEffects.None;
    }

    base.OnDragEnter(e);
    }

    private static Boolean IsDataValid(IDataObject data)
    {
    Boolean isValid = false;
    if (data != null)
    {
    String text = data.GetData(DataFormats.Text) as String;
    if (!String.IsNullOrEmpty(text == null ? null : text.Trim()))
    {
    Int32 result = -1;
    if (Int32.TryParse(text, out result))
    {
    if (result > 0)
    {
    isValid = true;
    }
    }
    }
    }

    return isValid;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
    if (e.Key < Key.D0 || e.Key > Key.D9)
    {
    if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
    {
    if (e.Key != Key.Back)
    {
    e.Handled = true;
    }
    }
    }
    }
    }
    }

    Hope this helps

    Thursday, February 21, 2008 5:08 AM
  • Thank you for posting this class. I hope it makes it into a future release as a native class.

     

    Can you provide an example of the XAML required to use this?

     

    Thanks, bob

    Monday, March 17, 2008 10:55 AM
  • Dear Marco,

    Thanks for your effort. However I found some problems in your implementation:

    Pressing Shift+Number will insert special characters, e.g. Shift+1 insert a !, Shift+2 inserts a @ etc.....also a space character can be inserted without problem....Is there any way to fix it? Thanks.
    Wednesday, June 4, 2008 2:19 PM
  • Marco,

    notice that TABs are suppressed.
    TAB is vital for desktop app.
    Tuesday, July 8, 2008 8:02 AM
  • Use following code in textbox key press event

    if (!Information.IsNumeric(e.KeyChar) && !char.IsControl(e.KeyChar)) e.Handled = true;

    Tuesday, July 14, 2009 11:24 AM
  • Supposing I'm including a NumberTextBox class in the project that inherits the TextBox class, in xaml it can be used like this:


    <Window x:Class="MyApp.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:MyApp"
    ...
    ...
    ...
    <local:NumberTextBox x:Name="MyTextBox"></local:NumberTextBox>
    ...
    ...
    ...
    • Proposed as answer by St3f Wednesday, August 5, 2009 9:43 AM
    Wednesday, August 5, 2009 9:19 AM
  • This is good enought for complete this, add an event handler for your textbox of PreviewTextInput event

    private void Number_PreviewTextInput(object sender, TextCompositionEventArgs e)
            {
                char c = e.Text.ToCharArray().First();
                e.Handled = !(char.IsNumber(c) || char.IsControl(c));
            } 


    And that is all

    Best regards,


    DarkFrost
    Microsoft Certified Proffesional
    Santiago - Chile

    Héctor Urbina Lopez - MCP (Santiago Chile)
    • Proposed as answer by DarkFrost Saturday, November 28, 2009 4:09 AM
    Saturday, November 28, 2009 3:56 AM
  • Can someone Explain how to implement DarkFrost's Method?? Little insight on How to use it and where to use it maybe?? 
    Wednesday, March 3, 2010 9:50 AM
  • Hi,

     

      Just add en event handler to the text box. In design mode, use properties and look for the event PreviewTextInput. Double click it to create the handler.   

    or manually add the handler (in the constructor) like this:

    textBox.PreviewTextInput += new TextCompositionEventHandler(your_handler);

     

    add the the snippet.

    hope it helps

     

     

     


    0g
    Wednesday, March 31, 2010 3:54 PM
  • Thank You, It really helped me...I am glad to see that Tab is also working....
    Thursday, April 1, 2010 3:38 AM
  • I recently solved this with these requirements:

    1. Allow pressing Numbers 1234567890 above QWERTY keys.
    2. Allow pressing Numpad numbers.
    3. Allow pressing of the Delete, Backspace, and Tab keys.
    4. Allow pasting so that only numbers in a string are added: A1B2C3 becomes 123.
    5. Allow drag and drop so that only numbers in a string are added: A1B2C3 becomes 123.
    6. Allow change in code at runtime so that only numbers in a string are added: A1B2C3 becomes 123.

    I would say my NumberTextBox is successful.

    Any body have any feedback:

    http://rhyous.com/2010/06/18/how-to-limit-or-prevent-characters-in-a-textbox-in-csharp/

     


    http://rhyous.com Never stop acquiring knowledge, as it goes with you when you die.
    • Proposed as answer by Rhyous Friday, June 18, 2010 8:00 AM
    Friday, June 18, 2010 7:52 AM
  • Gracias!!! Me sacaste de un apuro. SDs
    Wednesday, November 28, 2012 9:12 PM
  • //tb - is the name of text box
    // I think this is the easies way.
    // Can modify wherever you want.
    
    private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
    
            {
    char[] inputChar = e.Text.ToCharArray();
    if (char.IsNumber(inputChar[0]))
    
                {
    
                    e.Handled = 
    false;
                }
    else
                {
                    e.Handled = 
    true;
                }
    
    
    // another one.
    if (char.IsDigit(inputChar[0]))
                {
                    e.Handled = 
    false;
                }
    else
                {
                    e.Handled = 
    true;
                }
            }
    

    • Edited by ManojSunu Monday, December 3, 2012 11:35 AM
    • Proposed as answer by ManojSunu Monday, December 3, 2012 11:35 AM
    Monday, December 3, 2012 11:26 AM