我有一个textbox
只需要接受数字(可以是十进制值)和负值。
目前我有这样的KeyPress
事情
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
为了允许负值,我还应该做什么?
谢谢
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;
正如 LB 在评论中正确提到的那样,这将不允许一些高级符号,例如3E-2
,但对于简单的数字,它可以解决问题。
@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;
}
}
我已经分解了一些可以合并为一行的东西。但基本上你还需要检查文本中是否已经存在负号,以及用户是否将光标放在文本的开头。
我认为文本框有一个属性,您可以在其中设置所插入内容的输入。虽然我目前无法检查这一点。
否则,作为替代方案,您可以在提交值时尝试将输入解析为双精度值。就像是:
double myDouble;
try
{
myDouble = double.parse(textbox.Text)
}
catch (Exception e)
{
MessageBox.Show("Input is incorrect", "Error")
}
这可能不是最好的解决方法,但它可能只是解决问题。
连接 Validating 事件,如下所示:
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;
}
}
就像是:
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;
}
}
试试这个正则表达式
"/^(?!0*[.,]0*$|[.,]0*$|0*$)\d+[,.]?\d{0,2}$/"
并使用System.Text.RegularExpressions
命名空间
请参阅此处的示例:http: //msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx