只有数字的文本框 [英] TextBox with only numbers

查看:21
本文介绍了只有数字的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个只有数字的文本框,但我做不到.我试图输入: InputScope = "Numbers" 但这仅适用于移动设备.我也试过 TextChanging 这个:

I need to create a TextBox with only numbers but I couldn't do. I have tried to put : InputScope = "Numbers" but this only work on Mobile. Also I have tried on TextChanging this:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
    {

        textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    }
}

推荐答案

您可以阻止任何非数字输入,也可以过滤掉文本中的数字.

You can either prevent any non-numeric input whatsoever, or just filter out digits in the text.

防止非数字输入

使用 BeforeTextChanging 事件:

<TextBox BeforeTextChanging="TextBox_OnBeforeTextChanging" />

现在这样处理:

private void TextBox_OnBeforeTextChanging(TextBox sender,
                                          TextBoxBeforeTextChangingEventArgs args)
{
    args.Cancel = args.NewText.Any(c => !char.IsDigit(c));
}

此 LINQ 表达式将返回 true 并因此 Cancel 文本更改,以防在输入中遇到任何非数字字符.

This LINQ expression will return true and hence Cancel the text change in case it encounters any non-digit character in the input.

过滤非数字输入

使用 TextChanging 事件:

<TextBox TextChanging="TextBox_OnTextChanging" /> 

然后这样处理:

private void TextBox_OnTextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    //Save the position of the selection, to prevent the cursor to jump to the start
    int pos = sender.SelectionStart;
    sender.Text = new String(sender.Text.Where(char.IsDigit).ToArray());
    sender.SelectionStart = pos;
}

此 LINQ 查询将过滤掉非数字字符并仅使用输入中的数字创建一个新的 string.

This LINQ query will filter out non-digit characters and create a new string only with the digits in the input.

最好使用TextChangingBeforeTextChanging,因为TextChanged发生的太晚了,用户会因为看到字符暂时显示而感到困惑在屏幕上并立即消失.

It is preferable to use TextChanging and BeforeTextChanging, because TextChanged occurs too late, so the user would be confused by seeing characters temporarily display on the screen and immediately disappearing.

这篇关于只有数字的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆