将文本框输入限制为C#中的数字

ibr*_*him 3 c#

我想限制文本框只接受C#中的数字.我怎么做?

BFr*_*ree 13

这种做法最粗糙,最简单的做法就是:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar);
    }

}
Run Code Online (Sandbox Code Playgroud)

使用此方法仍然不安全,因为用户仍然可以将非数字字符复制并粘贴到文本框中.无论如何,您仍需要验证数据.

  • 用户也无法删除字符. (5认同)
  • 这很好用,我建议的唯一更改是启用 Backspace char: private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar= =8); } (2认同)