C# Numeric Only TextBox Control [duplicate]

2019-01-15 13:37发布

This question already has an answer here:

I am using C#.NET 3.5, and I have a problem in my project. In C# Windows Application, I want to make a textbox to accept only numbers. If user try to enter characters message should be appear like "please enter numbers only", and in another textbox it has to accept valid email id message should appear when it is invalid. It has to show invalid user id.

10条回答
We Are One
2楼-- · 2019-01-15 14:14

use this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }
查看更多
你好瞎i
3楼-- · 2019-01-15 14:14

I used the TryParse that @fjdumont mentioned but in the validating event instead.

private void Number_Validating(object sender, CancelEventArgs e) {
    int val;
    TextBox tb = sender as TextBox;
    if (!int.TryParse(tb.Text, out val)) {
        MessageBox.Show(tb.Tag +  " must be numeric.");
        tb.Undo();
        e.Cancel = true;
    }
}

I attached this to two different text boxes with in my form initializing code.

    public Form1() {
        InitializeComponent();
        textBox1.Validating+=new CancelEventHandler(Number_Validating);
        textBox2.Validating+=new CancelEventHandler(Number_Validating);
    }

I also added the tb.Undo() to back out invalid changes.

查看更多
叼着烟拽天下
4楼-- · 2019-01-15 14:14

You can check the Ascii value by e.keychar on KeyPress event of TextBox.

By checking the AscII value you can check for number or character.

Similarly you can write logic to check the Email ID.

查看更多
贪生不怕死
5楼-- · 2019-01-15 14:18

You might want to try int.TryParse(string, out int) in the KeyPress(object, KeyPressEventArgs) event to check for numeric values. For the other problem you could use regular expressions instead.

查看更多
登录 后发表回答