Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Limiting textBox Input in C#
#1
I've been working on a calculator to compare experience per level and cumaltive experience in the three experience curves MapleStory uses. On a KeyPress event for every input box, I call this method.
Code:
private void WhenaKeyIsPressed(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
            {
                e.Handled = true;
            }
        }
The idea was to limit the input to numbers, so I wouldn't have to make fancy checks for letters, but a few problems arose.

  1. Backspace does not work. To delete something, I have to arrow key behind it and press Delete.
  2. Decimals do not work. I want it to take a decimal value for percents, but it blocks the "." key too.
I Googled around for Regular Expressions and tried a multitude of different things, but everything gave errors. I tried reading on how to format them. Errors. I tried copypasting premade ones. Errors.

I need some help with this. I want to limit all the inputs to integers, except for two which I want limited to decimals rounded to the nearest hundredth. How can I do this with Regular Expressions or with another method?
Reply
#2
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Project
{
    public class NumberBox : TextBox
    {
        public NumberBox()
        {
            this.KeyPress += new KeyPressEventHandler(NumberBox_KeyPress);
        }
        private void NumberBox_KeyPress(object sender, KeyPressEventArgs kpe)
        {
            int KeyCode = (int)kpe.KeyChar;
            if (!IsNumberInRange(KeyCode, 48, 57) && KeyCode != 8)
            {
                kpe.Handled = true;
            }
        }
        private bool IsNumberInRange(int Val, int Min, int Max)
        {
            return (Val >= Min && Val <= Max);
        }
    }
}

This is a special textbox class that only allows numerical input. It uses the KeyPress event and compares the keycode to valid inputs; it therefore allows the use of backspace and all numerics, but I do not believe it allows for decimals. I believe you can simply find what keycode the period is on and set that to allow, and have another check somewhere to disable the use of more than one decimal for this.
Reply
#3
It took me a little bit to figure out how to use that, but now it works marvelously. Thank you very much.
Reply
#4
With that NumberBox, the user can still right-click and paste anything into it. A better solution imo is to allow anything to be typed, validate the text whenever you need to use it, and if you want to be fancy, indicate invalid inputs visually with a different color or something. There's also the built-in NumericUpDown control. It lets you paste in non-numeric text but reverts it when it loses focus.
Reply
#5
JoeTang Wrote:
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Project
{
    public class NumberBox : TextBox
    {
        public NumberBox()
        {
            this.KeyPress += new KeyPressEventHandler(NumberBox_KeyPress);
        }
        private void NumberBox_KeyPress(object sender, KeyPressEventArgs kpe)
        {
            int KeyCode = (int)kpe.KeyChar;
            if (!IsNumberInRange(KeyCode, 48, 57) && KeyCode != 8)
            {
                kpe.Handled = true;
            }
        }
        private bool IsNumberInRange(int Val, int Min, int Max)
        {
            return (Val >= Min && Val <= Max);
        }
    }
}

This is a special textbox class that only allows numerical input. It uses the KeyPress event and compares the keycode to valid inputs; it therefore allows the use of backspace and all numerics, but I do not believe it allows for decimals. I believe you can simply find what keycode the period is on and set that to allow, and have another check somewhere to disable the use of more than one decimal for this.
Not trying to be picky or anything, but what if you paste an input containing characters in there? when creating a software you must completely protect yourself from every possible way a user can make the program crash. This is a number-only implementation of TextBox coded by Koolk, mostly using a PreProcessMessage override:

Code:
using System;
    using System.Windows.Forms;

    public class KoolkTextBox : TextBox
    {
        private int Field_00 = 0x100;
        private int Field_01 = 770;

        protected override void WndProc(ref Message A_0)
        {
            if (A_0.Msg == this.Field_01)
            {
                string data = (string) Clipboard.GetDataObject().GetData(typeof(string));
                string str2 = data;
                int num = 0;
                do
                {
                    char c = str2[num];
                    if (!char.IsDigit(c))
                    {
                        A_0.Result = IntPtr.Zero;
                        return;
                    }
                    num++;
                }
                while (num < str2.Length);
            }
            base.WndProc(ref A_0);
        }

        public override bool PreProcessMessage(ref Message msg)
        {
            bool flag = true, flag2 = true, flag3 = true, flag4 = true, flag5 = true, flag6 = true;
            if (msg.Msg != this.Field_00)
            {
                return base.PreProcessMessage(ref msg);
            }
            Keys keys = (Keys) msg.WParam.ToInt32();
            if (((keys < Keys.D0) || (keys > Keys.D9)) && ((keys < Keys.NumPad0) || (keys > Keys.NumPad9)))
            {
                flag = false;
            }
            flag2 = keys == Keys.Control;
            if (keys != Keys.Z)
            {
                flag3 = false;
            }
            if (keys != Keys.X)
            {
                flag4 = false;
            }
            if (keys != Keys.C)
            {
                flag5 = false;
            }
            if (keys != Keys.V)
            {
                flag6 = false;
            }
            bool flag7 = keys == Keys.Delete;
            bool flag8 = keys == Keys.Back;
            bool flag9 = (((keys == Keys.Up) | (keys == Keys.Down)) | (keys == Keys.Left)) | (keys == Keys.Right);
            if (!(((((((flag | flag2) | flag7) | flag8) | flag9) | flag5) | flag4) | flag3))
            {
                if (!flag6)
                {
                    return true;
                }
                string data = (string) Clipboard.GetDataObject().GetData(typeof(string));
                string str2 = data;
                int num = 0;
                do
                {
                    char c = str2[num];
                    if (!char.IsDigit(c))
                    {
                        return true;
                    }
                    num++;
                }
                while (num < str2.Length);
            }
            return false;
        }
    }
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)