Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 仅允许数字和负值_C#_.net_Winforms - Fatal编程技术网

C# 仅允许数字和负值

C# 仅允许数字和负值,c#,.net,winforms,C#,.net,Winforms,我有一个文本框,它只需要接受数字(可以是十进制值)和负值 目前我在KeyPress事件中有类似的内容 if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') { e.Handled = true; } 为了允许负值,我还应该做什么 谢谢我认为文本框有一个属性,您可以在其中设置所插入内容的输入

我有一个
文本框
,它只需要接受数字(可以是十进制值)和负值

目前我在
KeyPress
事件中有类似的内容

   if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;                
    }
为了允许负值,我还应该做什么


谢谢

我认为文本框有一个属性,您可以在其中设置所插入内容的输入。虽然我目前无法检查这一点

否则,您可以在提交值时尝试将输入解析为double。比如:

double myDouble;
try
{
    myDouble = double.parse(textbox.Text)
}
catch (Exception e)
{
    MessageBox.Show("Input is incorrect", "Error")
}
var regex = new Regex("^[-]?\d+(\.\d+)?$", RegexOptions.Compiled);
Match m = regex.Match(textbox.Text + e.KeyChar);
e.Handled = m.Success;
这可能不是最好的解决办法,但它可能会奏效

if (!char.IsControl(e.KeyChar) && (!char.IsDigit(e.KeyChar)) 
        && (e.KeyChar != '.')  && (e.KeyChar != '-'))
    e.Handled = true;

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

// only allow minus sign at the beginning
if (e.KeyChar == '-' && (sender as TextBox).Text.Length > 0)
    e.Handled = true;
正如L.B在评论中正确提到的,这不允许使用一些高级符号,如
3E-2
,但对于简单的数字,它会起作用。

类似于:

double myDouble;
try
{
    myDouble = double.parse(textbox.Text)
}
catch (Exception e)
{
    MessageBox.Show("Input is incorrect", "Error")
}
if (!char.IsControl(e.KeyChar) && (!char.IsDigit(e.KeyChar)) 
        && (e.KeyChar != '.')  && (e.KeyChar != '-'))
    e.Handled = true;

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

// only allow minus sign at the beginning
if (e.KeyChar == '-' && (sender as TextBox).Text.Length > 0)
    e.Handled = true;
var regex = new Regex("^[-]?\d+(\.\d+)?$", RegexOptions.Compiled);
Match m = regex.Match(textbox.Text + e.KeyChar);
e.Handled = m.Success;
编辑:它现在允许任何实数

//用于确定何时输入数字以外的字符的布尔标志。
// Boolean flag used to determine when a character other than a number is entered. 
        private bool nonNumberEntered = false;

        // Handle the KeyDown event to determine the type of character entered into the control. 
        private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            // Initialize the flag to false.
            nonNumberEntered = false;

            // Determine whether the keystroke is a number from the top of the keyboard. 
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad. 
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace. 
                    if(e.KeyCode != Keys.Back)
                    {
                        // A non-numerical keystroke was pressed. 
                        // Set the flag to true and evaluate in KeyPress event.
                        nonNumberEntered = true;
                    }
                }
            }
            //If shift key was pressed, it's not a number. 
            if (Control.ModifierKeys == Keys.Shift) {
                nonNumberEntered = true;
            }
        }

        // This event occurs after the KeyDown event and can be used to prevent 
        // characters from entering the control. 
        private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            // Check for the flag being set in the KeyDown event. 
            if (nonNumberEntered == true)
            {
                // Stop the character from being entered into the control since it is non-numerical.
                e.Handled = true;
            }
        }
私有bool nonnumberrentered=假; //处理KeyDown事件以确定输入控件的字符类型。 私有void textBox1\u KeyDown(对象发送方,System.Windows.Forms.KeyEventArgs e) { //将标志初始化为false。 非numberrentered=false; //确定击键是否为键盘顶部的数字。 如果(e.KeyCodeKeys.D9) { //确定击键是否为键盘上的数字。 if(e.KeyCodeKeys.NumPad9) { //确定击键是否为退格。 if(e.KeyCode!=Keys.Back) { //按下了非数字按键。 //将标志设置为true并在按键事件中计算。 非numberrentered=真; } } } //如果按下shift键,则不是数字。 if(Control.ModifierKeys==Keys.Shift){ 非numberrentered=真; } } //此事件发生在按键按下事件之后,可用于防止 //禁止输入控件中的字符。 私有无效文本框1u按键(对象发送方,System.Windows.Forms.KeyPressEventArgs e) { //检查KeyDown事件中设置的标志。 if(非numberEntered==true) { //停止将字符输入控件,因为它不是数字。 e、 已处理=正确; } }
连接验证事件,如下所示:

private void myTextBox_Validating(object sender, CancelEventArgs event) {
    decimal d;
    if(!decimal.TryParse(myTextBox.Text, out d) {
        event.Cancel = true;
        //this.errorProvider1.SetError(myTextBox, "My Text Box must be a negative number."); //optional
        return;
    }

    if(d >= 0) {
        event.Cancel = true;
        //this.errorProvider1.SetError(myTextBox, "My Text Box must be a negative number."); //optional
        return;
    }
}

试试这个正则表达式

"/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/" 
并使用
System.Text.RegularExpressions
名称空间


请看这里的例子:

@DennisTraub的作品,但是它忽略了一些角落案例。例如,如果文本框中的文本为“-11”,并且用户将光标放在文本的开头,则他或她可以输入另一个字符,这样文本可以是“1-11”或“-11”。这是他的答案的延伸,似乎对我有用

TextBox textBox = sender as TextBox;
// If the text already contains a negative sign, we need to make sure that 
//    the user is not trying to enter a character at the start
// If there is already a negative sign and the negative sign is not selected, the key press is not valid
// This allows the user to highlight some of the text and replace it with a negative sign
if ((textBox.Text.IndexOf('-') > -1) && textBox.SelectionStart == 0 && !textBox.SelectedText.Contains('-'))
{
    e.Handled = true;
}
// Do not accept a character that is not included in the following
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '-')
{
    e.Handled = true;
}
// Only allow one decimal point
if ((e.KeyChar == '.') && (textBox.Text.IndexOf('.') > -1))
{
    e.Handled = true;
}            
// The negative sign can only be at the start
if ((e.KeyChar == '-'))
{
    // If the cursor is not at the start of the text, the key press is not valid
    if (textBox.SelectionStart > 0)
    {
        e.Handled = true;
    }
    // If there is already a negative sign and the negative sign is not selected, the key press is not valid
    // This allows the user to highlight some of the text and replace it with a negative sign
    if (textBox.Text.IndexOf('-') > -1 && !textBox.SelectedText.Contains('-'))
    {
        e.Handled = true;
    }
}

我把一些东西拆了出来,可以合并成一行。但基本上,您还需要检查文本中是否已经有负号,以及用户是否将光标放在文本的开头。

您可以使用正则表达式。只需使用keypress事件解析输入的文本并根据正则表达式验证它:^\d+$这个有效的double
3E-2
?@L.B你说得对,那不起作用。但是我没有在这里假设这种边缘情况。大多数欧洲国家使用
作为十进制分隔符,“3,5”也可能是3的有效双精度。5@DennisTraub-是否可以在文本框中只输入数字和减号进行验证?这个有效的双精度
3E-2
?@L.B,尽管他刚才在说“数字”如问题中的整数:
可以是十进制值
@derape:是的,它应该允许十进制值作为well@huMptyduMpty:我的答案只允许十进制值,所以我更新了它,允许所有的“实数”“数字:123,-123.45,123.45,etcI将使用
double.TryParse
而不是获取无效值的异常。
bool b=Regex.IsMatch(“33”,@/^(?0*[,]0*$|[,]0*$|]\d+[,.]?\d{0,2}$/”bool b=Regex.IsMatch(“33”,@“^(?0*[,]0*$|[,]0*$| 0*$)\d+[,.]?\d{0,2}$”;现在它不适用于
1000000.5
(取决于当前的文化,它可能是1000.000,5),而且,它也存在负值问题ADD-?在表达式的开头..使用此^-?(?!0*[,]0*$|[,]0*$| 0*$)\d+[,.]?\d{0,2}$