How to make a textbox that can limit the user can only write the input from 0000 to FFFF only. c#

Viewed 52

This is the code I write that only accepts numbers or only characters. I dk the way that can only limit the user can only write the input from 0000 to FFFF only.

Please Guide me Thank You

public partial class TextBox_Numbers_Characters : Form
{
    public TextBox_Numbers_Characters()
    {
        InitializeComponent();
    }

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

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

You can accomplish this by using one of the following statements.

I also added Ctrl + C, Ctrl + X and Ctrl + V exceptions, so the user is still able to copy and paste inside the specific input field.

char c = e.KeyChar;

if ((c==Keys.V && e.Control) || (c==Keys.C && e.Control) || (c==Keys.X && e.Control)) {
    e.Handled = true;
}
else {
    if (!(Char.IsControl(e.c)|| (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
   {
   e.Handled = true;
   }
}

You can also do it using this method.

Add the following to your XAML

<TextBox PreviewTextInput="OnPreviewTextInput">

Then implement this in your .cs file

private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    int hexNumber;
    e.Handled = !int.TryParse(e.Text, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out hexNumber);
}
Related