KeyUp event with TextBox

  • Thread starter Thread starter JPSutor
  • Start date Start date
J

JPSutor

I currently have this code in my kepup event of a text box. It works
except for the fact that if the number
25,000 or any number is put in then the user arrows to the left of the
third zero and tries to replace the number 0 with a 4, this is the
result
25,004

Here is my code. Any help would be appreciated.

public static void KeyStroke_FormatNumericText(string number,TextBox
txtBx) {

try {
long iReturn
=Int64.Parse(number,System.Globalization.NumberStyles.AllowThousands);
txtBx.Text = iReturn.ToString("#,0");
txtBx.SelectionStart = txtBx.Text.Length;
}
catch(Exception ex) {
Debug.WriteLine(ex.ToString());
}
}
 
Hi JPSutor,

Could you explain what your goal with the TextBox is as my attempts to
test your code resulted in a TextBox that only shows a single number at a
time. Could you show us your KeyUp event as well?
 
Alright, I passed the Key value as a parameter to the method instead of
the whole text.
If I understand your problem correctly, it does not handle moving the
arrow keys and trying to replace specific digits correctly.

This is caused by the fact that even the arrow keys are considered input
and the marker is pushed back to the end. Try calling the method for
certain keys only, something like

private void tb_KeyUp(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.D0:
case Keys.D1:
case Keys.D2:
case Keys.D3:
case Keys.D4:
case Keys.D5:
case Keys.D6:
case Keys.D7:
case Keys.D8:
case Keys.D9:
case Keys.Back:
case Keys.Delete:
KeyStroke_FormatNumericText(tb.Text,tb);
break;
}
}

A better way might be to set a flag in the KeyPress event if
Char.IsDigit(e.KeyChar) and call the method in the keyup event only if the
flag is set or Keys.Delete or Keys.Back is entered. This would be better
as the above code will let through [SHIFT]+Keys.D0 etc while also ignoring
Numpad keys.

Or you could store the TextBox string somewhere and compare it in the
keyup event, if it is changed, call the method.
 
Back
Top