问题
I have a textbox that gets a decimal value say 10500.00
the problem is that the way I have it, when you enter a value and then enter the decimals it would not allow you to backspace or clear the textbox to input a new value.. it just gets stuck.. I have tried to set the value back to 0.00 but i think i placed it on the wrong place because it wont change it. Here is my code
private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @"\.\d\d");
if (matchString)
{
e.Handled = true;
}
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;
}
}
What type of change do you suggest so that I may be able to backspace or clear the texbox an enter a new value?.
回答1:
You can trap for the Backspace (BS) char (8) and, if found, set your handle to false.
Your code may look like this...
....
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == (char)8)
e.Handled = false;
A suggestion to make your code a bit more intuitive to interpret what your event handler is doing, you may want to create a var that implies the logic you are implementing. Something like...
private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
bool ignoreKeyPress = false;
bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @"\.\d\d");
if (e.KeyChar == '\b') // Always allow a Backspace
ignoreKeyPress = false;
else if (matchString)
ignoreKeyPress = true;
else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
ignoreKeyPress = true;
else if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
ignoreKeyPress = true;
e.Handled = ignoreKeyPress;
}
回答2:
Easiest way would be :
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '\b')
{
e.Handled = true;
}
来源:https://stackoverflow.com/questions/10039338/textbox-with-decimal-input-improvement