温馨提示×

C# TextBox中只能输入数字的方法有哪些

小亿
100
2024-01-19 10:30:14
栏目: 编程语言

C#中只允许输入数字的方法有以下几种:

  1. 使用KeyPress事件:可以使用KeyPress事件来过滤输入,只允许数字输入。在KeyPress事件中,可以通过判断输入的字符是否是数字来决定是否接受输入。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}
  1. 使用TextChanged事件:可以使用TextChanged事件在每次文本框内容发生变化时检查输入是否为数字,并在必要时进行处理。
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (!int.TryParse(textBox1.Text, out int result))
    {
        textBox1.Text = "";
    }
}
  1. 使用正则表达式:可以使用正则表达式来验证输入是否为数字,并在必要时进行处理。
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (!Regex.IsMatch(textBox1.Text, @"^\d+$"))
    {
        textBox1.Text = "";
    }
}

以上方法可以根据具体需要选择其中一种或多种来实现只允许数字输入的功能。

0