Restrict TextBox input - C#

This article describes how to restrict TextBox input in order to accept only integers (0 - 9) or only characters (a-z A-Z) or only Arabic characters.

restrict textbox input c#

1. Restrict TextBox input to allow only numbers:

In KeyPress event of the TextBox we add this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
    {
        e.Handled = true;
    }
}

2. Restrict TextBox input to allow only characters:

In KeyPress event of the TextBox we add this code which allows only characters (a-z A-Z, white space and back space):

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space);
}

3. Restrict TextBox input to allow Arabic Characters only:

In KeyPress event of the TextBox we add this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    char lastChar = e.KeyChar;
    if (e.KeyChar != 32 && e.KeyChar != 8)
    {
        if (char.IsControl(lastChar) || char.IsDigit(lastChar) || char.IsNumber(lastChar) || char.IsPunctuation(lastChar))
            e.Handled = true;
        else if (lastChar < 1569)
            e.Handled = true;
    }
}

To understand more, check this video:


Restrict TextBox input - C# Restrict TextBox input - C# Reviewed by Bloggeur DZ on 02:23 Rating: 5

Aucun commentaire:

Fourni par Blogger.