I have a textbox that accepts only these values:
. , – $ m M k K b B and numbers
It also only accepts at most two decimal places. My problem is that after I tab off the textbox and then select it again, I am unable to type any information or overwrite whatever exists already in the textbox.
/// Checks if the decimal places are more than 2 and it will not allow user to keyin if its more than 2.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtAmount_KeyDown(object sender, KeyEventArgs e)
{
string textValue = txtAmount.Text.Trim();
if (textValue.IndexOf(".") > 0)
{
string[] decimalvalue = textValue.Split(new char[] { '.' });
if (decimalvalue[1].Length >= 2)
cancelCharacter = true;
else
cancelCharacter = false;
}
}
/// <summary>
/// Doesn't allow the user to enter any other value other than
/// ". , - $ m M k K b B and numbers"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) &&
e.KeyChar != 46 && e.KeyChar != 36 && e.KeyChar != 36 && e.KeyChar != 32 && e.KeyChar != 44 && e.KeyChar != 8 && e.KeyChar != 45 &&
e.KeyChar != 75 && e.KeyChar != 107 && e.KeyChar != 77 && e.KeyChar != 109 && e.KeyChar != 66 && e.KeyChar != 98)
{
e.Handled = true;
}
else if (cancelCharacter && e.KeyChar != 8 && e.KeyChar != 45 &&
e.KeyChar != 75 && e.KeyChar != 107 && e.KeyChar != 77 && e.KeyChar != 109 && e.KeyChar != 66 && e.KeyChar != 98)
{
e.Handled = true;
}
else if (e.KeyChar == '.' && txtAmount.Text.IndexOf(".") > -1 || cancelCharacter && e.KeyChar != 8)
{
e.Handled = true;
}
}
Looks like you need to reset your cancelCharacter flag. Handle the
Leaveevent:How about this. Change to this line in you keydown event to watch for how many characters are selected: