【问题标题】:Specific characters in textbox文本框中的特定字符
【发布时间】:2020-08-09 18:50:03
【问题描述】:

我想让 C# 中的文本框只接受数字、一个小数点和一个负号,就在文本框的开头,我试试这个代码:

 var txt = (TextBox)sender;

        if(e.KeyChar == 46 && txt.Text.IndexOf('.')!=-1)
        {
            e.Handled = true;
            return;
        }

        if(!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
        {
            e.Handled = true;
        }
        else
        {
            e.Handled = false;
        }

        if (e.KeyChar == 45 && (sender as TextBox).Text.Length > 0)
        {
            e.Handled = true;
        }

负号无效,你能帮帮我吗?

【问题讨论】:

  • 哪个 UI 框架(WinForms、WPF、Xamarin、ASP.NET)?你用你的代码处理哪个事件?你有什么问题?
  • @KlausGütter 是正确的。给我们一些关于你的问题的其他细节。因为它在每个平台上处理验证的方法不同。干杯!
  • 这是新项目的默认方式>>> windows窗体应用程序(.net框架)

标签: c# character-encoding textbox


【解决方案1】:

您可以在 KeyPress 事件中考虑这种方法:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        var txt = (TextBox)sender;
        var newText = string.Concat(txt.Text, e.KeyChar);
        if (newText.ToArray().Count(t => t == '.') < 2 && newText.EndsWith("."))
            newText = newText.Remove(newText.Length - 1);

        if (newText == "-" || e.KeyChar == '\b')    
        {
            e.Handled = false;
            return;
        }

        var isvalid = Regex.IsMatch(newText, @"^-?[0-9]\d*(\.\d+)?$");
        if (isvalid)
            e.Handled = false;
        else
            e.Handled = true;
    }

【讨论】:

  • wooow,非常感谢.....非常好的解决方案,,,,再次感谢您
  • 太棒了!您也可以检查表单选项卡控件的选项卡 KeyChar。
猜你喜欢
  • 2012-09-18
  • 2014-06-14
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 2020-11-12
  • 2021-04-28
相关资源
最近更新 更多