【问题标题】:Allow only {'delete' , 'backspace' , one '.' , '-' , numbers '0 to 9'} on a textbox C#/winforms只允许 {'delete' , 'backspace' , 一个 '.' , '-' , numbers '0 to 9'} 在文本框 C#/winforms
【发布时间】:2021-11-20 18:50:00
【问题描述】:

我是一名初学者程序员,我正在尝试修改以下代码,以便只允许 {'delete' , 'backspace' , one '.' ,输入开头的一个“-”号,文本框 C#/winforms 上的数字“0 到 9”}:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
            e.Handled = true;
    }

    // only allow one decimal point
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }
} 

请帮忙?

【问题讨论】:

  • 这是可能的,但它确实是 AWFUL 的可用性。通常,您最好更多允许任何击键,在完成操作(按钮单击、页面提交等)时检查它,并仅使用 keypress 事件来显示即时反馈最终结果是否可以,不干扰用户。
  • 改用MaskedTextBox
  • 即使代码看起来不太可读或不是最佳的,您也应该使用 OR 运算符检查键。如果您使用 AND 运算符,您的代码将检查是否满足所有条件。查看文档:docs.microsoft.com/de-de/dotnet/api/…
  • @JoelCoehoorn 我正在尽量减少要求我做这个限制的低学历木匠的打字错误,所以我为我的小工具中的每个文本框考虑了这种简单的方法,所以这对他们来说是可以接受的,对我作为初学者来说也很容易。
  • @LarsTech 我会搜索一下,尽量理解,谢谢建议

标签: c# .net winforms textbox


【解决方案1】:

以下方法检查输入的字符是否允许:

private bool NotPermittedChar(char character)
{
    return !char.IsDigit(character) && 
        !character.Equals('-') && 
        !character.Equals('.') && 
        !char.IsControl(character);
}

那么下面的 KeyPress 方法代码会执行你需要的相关检查和条件:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (this.NotPermittedChar(e.KeyChar))
    {
        e.Handled = true;
        return;
    }

    if (this.textBox1.Text.Contains(".") && e.KeyChar.Equals('.'))
    {
        e.Handled = true; //// Don't allow more than 1 decimal place
        return;
    }

    if (this.textBox1.SelectionStart == 0 && e.KeyChar.Equals('.'))
    {
        e.Handled = true; //// Don't allow . to be at the beginning
        return;
    }

    if (this.textBox1.SelectionStart != 0 && e.KeyChar.Equals('-'))
    {
        e.Handled = true; //// Don't allow - in other index than the beginning
        return;
    }
}

我在e.Handled 旁边添加了一些 cmets,所以你知道正在检查哪个条件,根据我的测试,这一切似乎都有效。

【讨论】:

  • 谢谢,效果很好!
  • 很高兴我能帮上忙 :)
【解决方案2】:

这个问题与this one 非常相似,除了你有允许- 的附加要求

所以试试这个

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar))  //bypass control keys
    {
        int dashIndex = textBox1.Text.IndexOf('-');
        int dotIndex = textBox1.Text.IndexOf('.');
        int selectionStart = textBox1.SelectionStart;
        int selectionEnd = selectionStart + textBox1.SelectionLength;

        if (char.IsDigit(e.KeyChar))
        {
            if (dashIndex == 0 && selectionStart == 0 && selectionEnd == 0)
                e.Handled = true;
        }
        else if (e.KeyChar == '-')
        {
            if (dashIndex == -1)
            {
                if (selectionStart != 0)
                    e.Handled = true;
            }
            else
                e.Handled = !(selectionStart <= dashIndex && selectionEnd > dashIndex);
        }
        else if (e.KeyChar == '.')
        {
            if (dotIndex == -1)
                e.Handled = false;
            else
                e.Handled = !(selectionStart <= dotIndex && selectionEnd > dotIndex);
        }
        else
            e.Handled = true;
    }
}

【讨论】:

  • 感谢您的回答,我试过了,它不接受点并且接受多个 (-) 无论输入中 (-) 的索引是什么
  • @Baibers 老实说,当我写这个答案时,你的问题有{'delete' , 'backspace' , one '.' , '-' , numbers '0 to 9'},你已经编辑过了。所以一个'-'是一个新的要求,但你应该能够应用与'.'相同的逻辑。我发布的代码也接受点(句点),除非你放一个不同的“点”
  • 对不起,文本框只能接受带有退格和删除的正负双打,我是初学者,有时我解释的方式不好
  • @Baibers 我根据要求更新了答案。您现在已经明确表示您只需要带有或不带有- 的浮点数。老实说,你最好使用NumericUpDown,它只允许数字,但你会得到滚动箭头。但为什么要重新发明轮子呢?
【解决方案3】:

在我看来,您希望让操作员能够编辑一个可能为负数的精确到一个小数点。

您的建议是在输入每个字符后立即检查它,并允许或禁止该字符。这提供了一个相当笨拙的用户界面。

  • 运算符类型 9876
  • 哦不,这是错误的数字,我需要 -76"
  • 操作员使用方向键返回7之前,输入减号(中间:98-76),使用方向键向左移动一位,delete删除删除98(中间: 9-76, -76)

复制粘贴其他值“价格 €76.12”并删除不需要的字符 (76.12) 是不可能的。

正确的界面应该是允许操作员完成所有操作,直到他向您发出他已完成编辑号码的信号。通常这是一个确定按钮,或者如果您想要输入按钮。订阅正确的事件,然后才处理输入:

public void OnButtonOk_Clicked(object sender, ...)
{
    string inputText = this.textBox1.Text;
    this.ProcessInput(inputText);
}

// or if you want: react on enter:
public void OnKeyPress(object sender, ...)
{
    // check if enter
    bool enterPressed = ...
    if (enterPressed)
    {
        this.ProcessInput(this.textBox1.Text);
    }
}

public void ProcessInput(string inputText)
{
    // check if the text can be converted to a double:
    if (double.TryParse(inputText, double result))
    {
         // text ok: do what you need to do
    }
    else
    {
         // text not ok: warn the operator
    }
}

【讨论】:

  • 我有许多文本框和许多按钮,它们从文本框中获取输入并继续工作,所以我更喜欢从一开始就限制输入错误,但无论如何谢谢你,我可能在其他依赖输入形式中需要这个
  • 如果您有按钮-texbox 组合,请考虑创建一个包含此组合的用户控件。或者考虑从文本框派生并检查派生类中的输入,以便您可以将代码重用于其他文本框
猜你喜欢
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 2010-11-10
  • 1970-01-01
  • 2016-06-30
相关资源
最近更新 更多