简体   繁体   English

在文本框 C#/winforms 上只允许 {'delete', 'backspace', one '.', '-', numbers '0 to 9'}

[英]Allow only {'delete' , 'backspace' , one '.' , '-' , numbers '0 to 9'} on a textbox C#/winforms

I am a beginner programmer and I am trying to modify the following code in order to allow only {'delete', 'backspace', one '.', one '-' sign in the beginning of input, numbers '0 to 9'} on a textbox C#/winforms:我是一名初学者程序员,我正在尝试修改以下代码以仅允许 {'delete', 'backspace', one '.', one '-' sign in the beginning of input, numbers '0 to 9' } 在文本框 C#/winforms 上:

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;
    }
} 

any help please?有什么帮助吗?

The question is very similar to this one except you have the added requirement of allowing -这个问题与这个问题非常相似,除了你有额外的要求允许-

So try this所以试试这个

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;
    }
}

It seems to me that you want to enable the operator to edit a possibly negative number with exactly one decimal point.在我看来,您想让操作员能够编辑一个可能为负数的小数点。

Your proposal is to check every input character as soon as it is typed, and allow or forbid the character.您的建议是在键入每个输入字符后立即检查它,并允许或禁止该字符。 This gives a rather clumsy user interface.这提供了一个相当笨拙的用户界面。

  • Operator types 9876操作员类型 9876
  • Oh no, this is the incorrect number, I need -76"哦不,这是错误的数字,我需要 -76”
  • The operator uses the arrow keys to go back to before the 7, type the minus sign (intermediate: 98-76), use the arrow key to go one to the left, and delete delete to remove the 98 (intermediate: 9-76, -76)操作员用方向键go回到7前,打负号(中级:98-76),用方向键go向左一个,delete删除98(中级:9-76) , -76)

Copy paste other values "Price €76.12" and remove unwanted characters (76.12) is impossible.复制粘贴其他值“Price €76.12”并删除不需要的字符 (76.12) 是不可能的。

The proper interface would be, to allow the operator everything, until he signals you that he finished editing the number.正确的界面应该是允许操作员执行所有操作,直到他向您发出信号表示他已完成号码编辑。 Usually this is an OK button, or if you want the enter button.通常这是一个 OK 按钮,或者如果你想要 enter 按钮。 Subscribe to the proper event, and handle the input only then:订阅适当的事件,然后才处理输入:

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
    }
}

The below method checks if the Character entered is permitted:下面的方法检查是否允许输入的字符:

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

Then the below KeyPress method code will perform the relevant checks and conditions you require:然后下面的 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;
    }
}

I added some comments at the side of the e.Handled so you know which condition is being checked, it all seems to work according to my testing.我在e.Handled的旁边添加了一些注释,以便您知道正在检查哪个条件,根据我的测试,这一切似乎都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 C# 中的文本框中只允许十进制数字 - Allow only decimal numbers in textbox in C# 仅在文本框C#WinForms中允许特定的值格式 - Only allow a specific Value Format in a Textbox C# WinForms 如何在TextBox中允许并限制一个“。”(句点)字符? (C#Winforms) - How to allow, and limit to one “.” (period) character in a TextBox? (C# winforms) WinForms 文本框只允许 1 到 6 之间的数字 - WinForms Textbox only allow numbers between 1 and 6 如何只允许在文本框上按下数字、退格键和连字符键 - How to only allow the numbers ,backspace key and hypen key to be pressed on textbox 按下Backspace键时删除TextBox内容C# - Delete TextBox content when Backspace key is pressed C# C#Winforms中的文本框验证-应该只允许1-100之间的数字 - Textbox validation in C# Winforms - Should allow only numerics between 1-100 C# 仅含数字的文本框 - C# Textbox with numbers only C#Winforms - 允许表达式在文本框中并返回结果 - C# Winforms - allow expressions in a textbox and return result 如何将 C# 中的文本框限制为仅接收数字和(点“。”或逗号“,”),在“。”之后或 &quot;,&quot; 只允许 2 个数字字符 - How restrict textbox in C# to only receive numbers and (dot "." or comma ","), after "." or "," only allow 2 number characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM