Google Search is always a good place to start. I used:
winform textbox specific characters - Google Search[
^] and the first found was this solution:
Only allow specific characters in textbox [solved] - StackOverflow[
^]
UPDATE
To simplify the proposed solution in the link above, here is a simplified version of the accepted answer in the link provided. Only allows numerics, lower and upper case characters, and selected special characters. All other characters are ignored.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.KeyPress += OnKeyPress;
}
private void OnKeyPress(object? sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9')
return;
if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
return;
if (e.KeyChar >= 'A' && e.KeyChar <= 'Z')
return;
if ("\b".Contains(e.KeyChar))
return;
e.Handled = true;
}
}
Here is a more compact version using
Pattern Matching[
^]:
private void OnKeyPress(object? sender, KeyPressEventArgs e)
{
e.Handled = e.KeyChar switch
{
>= '0' and <= '9' => false,
>= 'a' and <= 'z' => false,
>= 'A' and <= 'Z' => false,
'\b' => false,
_ => true
};
}