仅允许数字和负值

huM*_*pty 5 .net c# winforms

我有一个textbox只需要接受数字(可以是十进制值)和负值.

目前我在KeyPress事件中有这样的事情

   if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;                
    }
Run Code Online (Sandbox Code Playgroud)

我还应该做些什么才能允许负值?

谢谢

Den*_*aub 8

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;
Run Code Online (Sandbox Code Playgroud)

正如LB在评论中正确提到的那样,这将不允许某些高级符号3E-2,但对于简单的数字,它将起到作用.