0
      if (!(char.IsDigit(e.KeyChar)))
     {
        e.Handled = true;
     }

The above code is not working properly

Below is the image error :

error

The problem space is "Clipboard"

ehsan_d18
  • 253
  • 1
  • 6
  • 12
  • Have you tested to see if the event is being fired on paste? I'm pretty sure it isn't. – enriquein Oct 06 '10 at 16:25
  • Possible duplicate of [How do I make a textbox that only accepts numbers?](http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – Simon Jensen Dec 29 '15 at 01:15

5 Answers5

6

If this is for WinForms, my suggestion would be to use a MaskedTextBox instead. This is a purpose-built control for allowing only certain kinds of user-input.

You can set the mask through the designer or in code. For example, for a 5-digit numeric:

maskedTextBox1.Mask = "00000";
maskedTextBox1.ValidatingType = typeof(int);
Ani
  • 111,048
  • 26
  • 262
  • 307
2

Yes, this is the typical nemesis for keyboard filtering. The TextBox control doesn't have any built-in events to intercept a paste from the clipboard. You'll have to detect the Ctrl+V keypress yourself and screen Clipboard.GetText().

The logic is tricky to get right. Here's a class that can make all this a little easier. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto a form. Double click it and write the ValidateChar event handler. Like this one, only allowing entering digits:

    private void validatingTextBox1_ValidateChar(object sender, ValidateCharArgs e) {
        if (!"0123456789".Contains(e.KeyChar)) e.Cancel = true;
    }

The code:

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;

[DefaultEvent("ValidateChar")]
class ValidatingTextBox : TextBox {
    public event EventHandler<ValidateCharArgs> ValidateChar;

    protected virtual void OnValidateChar(ValidateCharArgs e) {
        var handler = ValidateChar;
        if (handler != null) handler(this, e);
    }

    protected override void OnKeyPress(KeyPressEventArgs e) {
        if (e.KeyChar >= ' ') {   // Allow the control keys to work as normal
            var args = new ValidateCharArgs(e.KeyChar);
            OnValidateChar(args);
            if (args.Cancel) {
                e.Handled = true;
                return;
            }
        }
        base.OnKeyPress(e);
    }
    private void HandlePaste() {
        if (!Clipboard.ContainsText()) return;
        string text = Clipboard.GetText();
        var toPaste = new StringBuilder(text.Length);
        foreach (char ch in text.ToCharArray()) {
            var args = new ValidateCharArgs(ch);
            OnValidateChar(args);
            if (!args.Cancel) toPaste.Append(ch);
        }
        if (toPaste.Length != 0) {
            Clipboard.SetText(toPaste.ToString());
            this.Paste();
        }
    }

    bool pasting;
    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x302 && !pasting) {
            pasting = true;
            HandlePaste();
            pasting = false;
        }
        else base.WndProc(ref m);
    }
}

class ValidateCharArgs : EventArgs {
    public ValidateCharArgs(char ch) { Cancel = false; KeyChar = ch; }
    public bool Cancel { get; set; }
    public char KeyChar { get; set; }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

Handle TextChanged event or use a MaskedTextBox.

            if (textBox1.Text.Count(a => !char.IsDigit(a)) > 0)
        {
            textBox1.Text = new string(textBox1.Text.Where(a => char.IsDigit(a)).ToArray());
        }
as-cii
  • 12,819
  • 4
  • 41
  • 43
  • Ok but if you handle the textchanged event, clipboard or not, you know always the kind of text inside the textbox. – as-cii Oct 06 '10 at 16:52
0

I answered a similar question on StackOverflow once.
Here's the link to the question: Best way to limit textbox decimal input in c#

Essentially, you'll have to put my class in your code and apply it to all textboxes you want to restrict data entered.

The TextBoxFilter class I wrote allows you to limit entry to Alphabet, Numerics, AlphaNumerics, Currency and UserSpecified input.

Community
  • 1
  • 1
Alex Essilfie
  • 12,339
  • 9
  • 70
  • 108
0
control.TextChanged += (s, a) => {
    string value = string.Empty;
    foreach (char ch in control.Text.ToCharArray())
    {
        if (char.IsDigit(ch))
        {
            value += ch.ToString();
        }
    }
    control.Text = value;
};
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93