c# - 验证文本框只允许小数

标签 c# winforms

我正在使用以下代码来验证文本框。

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

public bool SingleDecimal(System.Object sender, char eChar)
{
    string chkstr = "0123456789.";
    if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack) 
    {
        if (eChar == ".") 
        {
            if (((TextBox)sender).Text.IndexOf(eChar) > -1) 
            {     
                return true;
            }
            else 
            {         
                return false;  
            }
        }   
        return false;
     }
     else 
     {
         return true;  
     }
}

问题是 Constants.vbBack 显示错误。如果我没有使用 Constants.vbBack,退格键不起作用。我可以做些什么来使退格键工作。有人可以帮忙吗?

最佳答案

这是我要使用的代码...

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // allows 0-9, backspace, and decimal
    if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
    {
        e.Handled = true;
        return;
    }

    // checks to make sure only 1 decimal is allowed
    if (e.KeyChar == 46)
    {
        if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
            e.Handled = true;
    }
}

关于c# - 验证文本框只允许小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2108616/

相关文章:

c# - 如何通过 Windows Phone 8 的 Web 浏览器传递自定义 header ?

c# - 尝试读取或写入 protected 内存。这通常表示其他内存已损坏 - 在某些 PC 中

C# 在winform上显示来自sql server的表

c# - 如何为通用列表 orderby 函数创建委托(delegate)?

c# - 在 Visual Studio 中管理大量重叠控件

c# - 当我将我的用户控件拖到设计 View 上时,Visual Studio 引发错误

c# - .NET 最小化到托盘并最小化所需资源

winforms - 在Windows窗体中查找空标签

c# - WPF ComboBox...如何设置 .Text 属性?

c# - 加载表单时禁用按钮并在关闭表单时启用按钮