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