4

Im new to programming and I dont know very much about but I'm making a calculator, and i want to use a textbox that only acepts numbers and decimals, and when the user paste text from the clipboard the textbox deletes any literal characters, like the MS calc.

Please take the time to explain each part so I can learn or write it and tell me what to search.

Thanks

EDIT: I'll make it more specific:

How can I make a numeric textbox in C#? I've used the masked textbox but it wont take decimals.

I've read things about overloading the OnKeyPress method so it will correct any wrong characters but I dont know to do it.

Jacob
  • 77,566
  • 24
  • 149
  • 228
Ricardo
  • 1,018
  • 2
  • 9
  • 13
  • In addition to the impression that this sounds like a typical homework question, it also appears to take the person answering (and his/her time) for granted. -1 – Cerebrus Feb 03 '09 at 19:32
  • Its a fair enough question, I thought. +1 – GWLlosa Feb 03 '09 at 19:45
  • While I agree that the asker should put some more efort into it, there is no clear indication that this is a homework question. – EBGreen Feb 03 '09 at 19:59

13 Answers13

13

Add an event handler for the textbox you want to be numeric only, and add the following code:

private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
{
   if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
   {
      e.Handled = false;
   }
   else
   {
      e.Handled = true;
   }
}

This allows for numbers 0 to 9, and also backspaces (useful IMHO). Allow through the '.' character if you want to support decimals

John Sibly
  • 22,782
  • 7
  • 63
  • 80
7

If you look closely, In Windows Calculator, the numbers are shown in a label not a textbox (It does not receive focus). The window receives keyboard events.

So look at KeyPressed and KeyDown events on the form.

Timur Fanshteyn
  • 2,266
  • 2
  • 23
  • 27
4

The easiest way :)

on Keypress event on your textbox


if ((e.KeyChar <= 57 && e.KeyChar >= 48) || e.KeyChar == 13 || e.KeyChar == 8)
{
}
else
{
     e.Handled = true;
}

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Timur Fanshteyn
  • 2,266
  • 2
  • 23
  • 27
2

There is a control in the framework which is specially made for numeric input : the NumericUpDown control. It also manages decimal values.

Guulh
  • 284
  • 2
  • 7
1
        if ("1234567890".IndexOf(e.KeyChar.ToString()) > 0)
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
Ash
  • 1,269
  • 3
  • 25
  • 49
0

useful for decimal numeric entry but has some bugs if (rightclick and paste) the other text. :D

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        string original = (sender as TextBox).Text;
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        if (e.KeyChar == '.')
        {
            if (original.Contains('.'))
                e.Handled = true;
            else if (!(original.Contains('.')))
                e.Handled = false;

        }
        else if (char.IsDigit(e.KeyChar)||e.KeyChar=='\b')
        {
            e.Handled = false;
        }

    }
0

Here's a custom control I made based off mahasen's answer. Put it in it's own class file and fix the namespace to whatever you want. Once you rebuild your solution it should show up as a new control in your Toolbox menu tab that you can drag/drop onto a Form.

using System;
using System.Linq;
using System.Windows.Forms;

namespace MyApp.GUI
{
    public class FilteredTextBox : TextBox
    {
        // Fields
        private char[] m_validCharacters;
        private string m_filter;
        private event EventHandler m_maxLength;

        // Properties
        public string Filter
        {
            get
            {
                return m_filter;
            }
            set
            {
                m_filter = value;
                m_validCharacters = value.ToCharArray();
            }
        }

        // Constructor
        public FilteredTextBox()
        {
            m_filter = "";
            this.KeyPress += Validate_Char_OnKeyPress;
            this.TextChanged += Check_Text_Length_OnTextChanged;
        }

        // Event Hooks
        public event EventHandler TextBoxFull
        {
            add { m_maxLength += value; }
            remove { m_maxLength -= value; }
        }

        // Methods
        void Validate_Char_OnKeyPress(object sender, KeyPressEventArgs e)
        {
            if (m_validCharacters.Contains(e.KeyChar) || e.KeyChar == '\b')
                e.Handled = false;
            else
                e.Handled = true;
        }
        void Check_Text_Length_OnTextChanged(object sender, EventArgs e)
        {
            if (this.TextLength == this.MaxLength)
            {
                var Handle = m_maxLength;
                if (Handle != null)
                    Handle(this, EventArgs.Empty);
            }
        }
    }
}

and just as a bonus I wanted it to auto-tab to another box after I entered 3 characters so I set the box's max length to 3 and in the Form code I hooked that TextBoxFull event and focused on the box beside it. This was to chain 4 filtered boxes together to enter an IP address. Form code for the first two boxes is below...

    private bool ValidateAddressChunk(string p_text)
    {
        byte AddressChunk = new byte();
        return byte.TryParse(p_text, out AddressChunk);
    }
    private void filteredTextBox1_TextBoxFull(object sender, EventArgs e)
    {
        var Filtered_Text_Box = (FilteredTextBox)sender;

        if (!ValidateAddressChunk(Filtered_Text_Box.Text))
            filteredTextBox1.Text = "255";
        else
            filteredTextBox2.Focus();
    }
    private void filteredTextBox2_TextBoxFull(object sender, EventArgs e)
    {
        var Filtered_Text_Box = (FilteredTextBox)sender;

        if (!ValidateAddressChunk(Filtered_Text_Box.Text))
            filteredTextBox2.Text = "255";
        // etc.
    }
Community
  • 1
  • 1
HodlDwon
  • 1,131
  • 1
  • 13
  • 30
0

here how to do this in vb.net

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim reg As New System.Text.RegularExpressions.Regex("[^0-9_ ]")
    TextBox1.Text = reg.Replace(TextBox1.Text, "")
End Sub

just fix the regex for your specific needs

Fredou
  • 19,848
  • 10
  • 58
  • 113
0

Research the MaskedTextBox.

The question is a little broad to explain everything. Try to focus the question if you want specifics because you're asking for a lot of the community to "explain each part." If you ask a few specific questions (and exclude the "please the the time to explain..."), you'll get better responses.

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
0

As far as I am aware there's nothing native in the .NET framework (2.0 at least) to do this. Your options would be:

  1. Create a custom control which inherits from the textbox control and only allows numeric input. This has the advantage that the control can be reused.
  2. Handle the KeyPress event and check the charCode to only allow numeric keystrokes. This is easier but much less reusable.
Simon
  • 6,062
  • 13
  • 60
  • 97
0

i would probably use a regular expression to screen out non-numerics.

pseudo code:

for (each item in the input string) {
   if (!match(some regular expression, item)) {
        toss it out
   } else {
        add item to text box or whatever you were going to do with it
   }

}
Brian Sweeney
  • 6,693
  • 14
  • 54
  • 69
0

You could use a plain textbox or label as the calculator display and just make sure the value (a string?) is always a number. For instance, you could keep a double and convert it to a string when you wish to display it.

Albert
  • 536
  • 3
  • 7
  • 16
-1

Being a novice you might be better off investing in a good third party toolkit. Radcontrols from Telerik for instance has a numeric textbox that will accomplish what you are looking for.

Nathan
  • 9
  • 4
  • 4
    No way! Being a novice he should definetly try to figure out how to do it himself. In fact, he'd be better off searching for an appropriate solution than just asking us here at SO. So much of being a good programmer is figuring out how to find the best approach. – Todd Friedlich Feb 03 '09 at 21:59