For WPF:
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!char.IsDigit(e.Text, e.Text.Length - 1)) e.Handled = true; }
For Windows Forms:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) ) e.Handled = true; }
source share