1

Please excuse me for asking this, I have looked at various different questions relating to this and I still can not get it to implement.

Using the answers I have looked at, I have gathered this, and applied this coding to my text box.

private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
            e.Handled = true;
    }

Now, when I proceed to run the program, I am still able to enter letters into it. I do not know what to do next, so any solution would be great. thanks.

Fadzitt
  • 19
  • 1
  • 1
  • 6
  • 1
    first: step through the code in debugger and make sure routine is being called – Mitch Wheat Jun 01 '13 at 09:17
  • If this is a windows form application why dont you use NumericUpDown control which will only allow numbers. – Kurubaran Jun 01 '13 at 09:18
  • Is there a special reason that you are using a textbox? The easiest way to restrict the input to numbers is to use numericUpDown instead of textBox. If you really need the textBox you might make create a string or a list containing all digits (and maybe decimal point) and then check if the string that you enter contains any other character – NDraskovic Jun 01 '13 at 09:19
  • 1
    The MSDN documenation for [Control.KeyPress](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx) has an example for it. – Dirk Jun 01 '13 at 09:24
  • 1
    @Coder, I'm using a textbox because it looks cleaner than the NumericUpDown. – Fadzitt Jun 01 '13 at 09:30
  • @Fadzitt have you used a debugger to see if that method is actually called like Mitch Wheat asked? – Dirk Jun 01 '13 at 09:32
  • @Dirk I do not know how to do that, otherwise I would do it. – Fadzitt Jun 01 '13 at 09:36
  • Is this WinForms or WPF? – Shakti Prakash Singh Jun 01 '13 at 09:37
  • @Fadzitt Please take a look at this small [debugging tutorial](http://www.dotnetperls.com/debugging) then. – Dirk Jun 01 '13 at 09:38
  • @ShaktiPrakashSingh Windows form, – Fadzitt Jun 01 '13 at 09:47

5 Answers5

8

Okay this is what i made just now, it works 100% just tested it.Note that my textBox is named serialTxtBox, you can change it to yours.

void serialTxtBox_TextChanged(object sender, EventArgs e)
        {
            bool enteredLetter = false;
            Queue<char> text = new Queue<char>();
            foreach (var ch in this.serialTxtBox.Text)
            {
                if (char.IsDigit(ch))
                {
                    text.Enqueue(ch);
                }
                else
                {
                    enteredLetter = true;
                }
            }

            if (enteredLetter)
            {
                StringBuilder sb = new StringBuilder();
                while (text.Count > 0)
                {
                    sb.Append(text.Dequeue());
                }                

                this.serialTxtBox.Text = sb.ToString();
                this.serialTxtBox.SelectionStart = this.serialTxtBox.Text.Length;
            }
        }

EDIT: Definitely you are doing something wrong. In your form constructor which is named like your form. In my case SerialGenerator, you need to initialize the event. In my case :

public SerialGenerator()
        {
            InitializeComponent();
            this.serialTxtBox.TextChanged += serialTxtBox_TextChanged;
        }

this will fire the method everytime someone enters something in your textBox. Make sure you rename it to your textbox's name

Georgi-it
  • 3,676
  • 1
  • 20
  • 23
  • I can still enter letters, I'm doing something wrong. would it be possible for you to help over teamviewer or similar? – Fadzitt Jun 01 '13 at 10:36
  • and we have it working, I honestly can't thank you enough. Sorry for not being the most helpful of people, but we all do start somewhere. – Fadzitt Jun 01 '13 at 10:48
  • I have to have 15 rep to upvote it, but believe me I tried to as soon as it worked. – Fadzitt Jun 01 '13 at 10:58
  • if to write on the beginning **var textBox = (TextBox) sender;** then it does not matter what name textbox has. – Sasha Dec 05 '13 at 15:04
1

You can try this:

private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
{
    if(!(Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)))
        { e.Handled = true; }
}

I don't think this is the best one, but you may make this work by tweaking a little, I guess. I don't have VS right now to check what would work.

EDIT: My bad. I think you can use the above one not on keypress but on textchanged event of the textbox. It's more like a tweak than a solution. Just to make you progress if you are stuck and don't get a better solution.

Update: Updated the code. Please check if this one helps you.

Shakti Prakash Singh
  • 2,414
  • 5
  • 35
  • 59
0

Try this one,hope this works

   private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        int asciiCode = Convert.ToInt32(e.KeyChar);
        if ((asciiCode >= 48 && asciiCode <= 57))
        {


        }
        else
       {                MessageBox.Show("Not allowed!");
            e.Handled = true;


        }
    }
Charlie
  • 4,827
  • 2
  • 31
  • 55
0

I have added events on code level, since there can be a possibility in your code not correctly event added to the control.

Note : The KeyPress event is not raised by noncharacter keys you need to use both KeyDown and KeyPress events

public partial class Form1 : Form
{
    private bool nonNumberEntered = false;
    public Form1()
    {
        InitializeComponent();
        textBox1.KeyDown+=new KeyEventHandler(textBox1_KeyDown);
        textBox1.KeyPress+=new KeyPressEventHandler(textBox1_KeyPress);
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (nonNumberEntered == true)
        {
            e.Handled = true;
        }
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        nonNumberEntered = false;

        if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
            {
                if (e.KeyCode != Keys.Back)
                {
                    nonNumberEntered = true;
                }
            }
        }
        if (Control.ModifierKeys == Keys.Shift)
        {
            nonNumberEntered = true;
        }
    }
}

REF : Control.KeyPress Event

Damith
  • 62,401
  • 13
  • 102
  • 153
0

Try this ...

private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
    {         
        int num = 0;
         e.Handled = !int.TryParse(e.KeyChar.ToString(), out num);

    }
matzone
  • 5,703
  • 3
  • 17
  • 20