Come menzionato in un commento (e un'altra risposta mentre scrivevo) è necessario registrare un gestore di eventi per catturare l'evento keydown o keypress su una casella di testo. Questo perché TextChanged viene generato solo quando il TextBox perde lo stato attivo
Il sotto espressione regolare permette di abbinare questi personaggi si desidera consentire
Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);
e questo fa il contrario e cattura i caratteri che non sono consentiti
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);
Non sto assumendo che ci sarà una singola corrispondenza in quanto qualcuno potrebbe incollare il testo nella casella di testo. nel qual caso cattura TextChanged
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0) {
//tell the user
}
}
e per convalidare la pressione dei tasti singoli
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for a naughty character in the KeyDown event.
if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
fonte
2012-09-26 17:32:15
ASP.NET? WinForms? WPF? Tutti questi possono usare C# e tutti sono diversi. – David
È un'applicazione Windows Form. –
Hai provato a creare un gestore di eventi per l'evento PropertyChanged che elimina il carattere se non è valido? –