Problem with Key Event Sequence

P

PaulV

Using 1,1, C#, Windows Form (actually a UI Type Editor).

I need to filter characters in a textbox to numbers and a decimal
point while allowing backspace and delete key strokes

The doc says: KeyDown, KeyPress, KeyUp.

I'm seeing KeyPress then KeyDown. If KeyDown KeyEventArgs.handled
behaved like KeyPress KeyPressEventArgs.handled I could work around
it.

It makes no difference in what order or where I wire the events.

Any thoughts?


Paul
 
C

Claes Bergefall

The following works for me. It's in VB but
it should be easy to translate to C#

Private Sub myTextBox_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs)
Dim singleInstanceChars As String = String.Empty
singleInstanceChars &=
System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
singleInstanceChars &=
System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign
singleInstanceChars &=
System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign
Dim validChars As String = "0123456789"
validChars &=
System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator
validChars &= singleInstanceChars
validChars &= Chr(8)
If singleInstanceChars.IndexOf(e.KeyChar) <> -1 AndAlso _
myTextBox.Text.IndexOf(e.KeyChar) <> -1 Then
' Single instance character already exist
e.Handled = True
ElseIf validChars.IndexOf(e.KeyChar) <> -1 Then
' Valid character
e.Handled = False
Else
' Invalid character
e.Handled = True
End If
End Sub

/claes
 
D

Double@Buck

Thanks Claes. Works great.

Paul

private void Validate_KeyPress_Decimal(object sender,
KeyPressEventArgs e)
{
string strInput =
((System.Windows.Forms.TextBox)sender).Text;

string singleInstanceChars = String.Empty;
string validChars = "0123456789";

singleInstanceChars +=
System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
singleInstanceChars +=
System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign;
singleInstanceChars +=
System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign;

validChars +=
System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator;
validChars += singleInstanceChars;
validChars += (char)8;

if (singleInstanceChars.IndexOf(e.KeyChar) !=
-1 && strInput.IndexOf(e.KeyChar) != -1)
e.Handled = true;

else if (validChars.IndexOf(e.KeyChar) != -1)
e.Handled = false;

else
e.Handled = true;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top