Sprache: C#
Da ich hier nur eine komplexere Variante gefunden habe, reiche ich noch eine Kurzversion nach:
Eine Textbox, welche nur die Eingabe von numerischen Zeichen und BackSpace erlaubt.
class NumTextBox:System.Windows.Forms.TextBox
{
//Constructor
public NumTextBox()
{
//Aufruf von Context Menü unterbinden.
this.ShortcutsEnabled = false;
//KeyPress Ereignis anmelden
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(NumTextBox_KeyPress);
}
void NumTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//Prüfung, ob eine Zahl oder BackSpace ausgelöst wurde
if ("1234567890b".IndexOf(e.KeyChar.ToString()) < 0)
{
//Bei Abweichung Ereignis verwerfen
e.Handled = true;
}
}
}
class NumTextBox:System.Windows.Forms.TextBox
{
//Constructor
public NumTextBox()
{
//Aufruf von Context Menü unterbinden.
this.ShortcutsEnabled = false;
//KeyPress Ereignis anmelden
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(NumTextBox_KeyPress);
}
void NumTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//Prüfung, ob eine Zahl oder BackSpace ausgelöst wurde
if ("1234567890b".IndexOf(e.KeyChar.ToString()) < 0)
{
//Bei Abweichung Ereignis verwerfen
e.Handled = true;
}
}
}
Alte URL:
/snippet/numtextbox-kurzversion/1444
Hallo Zusammen,
kann mir jemand erklären, warum ich den Ereignishändler „KeyPress“ nicht finde?
(Die Ereignishändler „KeyUp“ und „KeyDown“ sind zum Beispiel verfügbar)
Danke schön 🙂
Es handelt sich noch um ein Windows Forms-Snippet.
Unter WPF kannst du folgendes verwenden:
[code]
private void NumericTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (!Char.IsDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) & e.Key != Key.Back | e.Key == Key.Space)
{
e.Handled = true;
MessageBox.Show(„I only accept numbers, sorry. :(„, „This textbox says…“);
}
}
[/code]
Grüße
Martin