How to make a Textbox accept only the letters S and N?

Asked

Viewed 472 times

1

I’m studying about TextBox in C# and I have no idea how to do this function.

2 answers

3

What happens immediately is to intercept the pressed key, using the event KeyDown, and check which was.
If the key corresponds to S or N the implementation must return e.Handled = false;, otherwise return e.Handled = true;.

Unfortunately this is not enough, since the key space is not intercepted.
On the other hand there is the possibility that the text can be entered via Paste.

Thus, to deal with all possibilities, you must treat the following events:

  • Previewtextinput
  • Previewkeydown
  • Paste

and restrict the number of accepted characters to 1.

The "best" way for the implementation is to write a custom Textbox that you can use anywhere.

public class S_N_TextBox : TextBox
{

    public S_N_TextBox()
    {
        DataObject.AddPastingHandler(this, PastingHandler);
        MaxLength = 1;
    }

    private void PastingHandler(object sender, DataObjectPastingEventArgs e)
    {
        var pasteText = e.DataObject.GetData(typeof(string)) as string;
        //Garante que o texto inserido via paste é válido
        if (!IsValid(pasteText))
        {
            e.CancelCommand();
        }
    }

    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        if (IsValid(e.Text))
        {
            //A documentação recomenda que o método base seja chamado.
            base.OnPreviewTextInput(e);
            return;
        }
        e.Handled = true;

    }

    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        //Não permite o uso do espaço
        e.Handled = e.Key == Key.Space;
    }

    //Determina que texto pode ser aceite
    protected virtual bool IsValid(string input) => input == "S" || input == "N";
}

This class can be used as a basis for other restrictions you want a Textblox to have. You only have to change the method IsValid().

2


In the archive .xaml of his Window put the following code. What matters here is the event KeyDown="txtTest_KeyDown":

<TextBox x:Name="txtTest" KeyDown="txtTest_KeyDown" HorizontalAlignment="Left" Height="23" Margin="239,148,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="282"/>

Now, in the .cs of his Window, create the method txtTest_KeyDown as follows:

private void txtTest_KeyDown(object sender, KeyEventArgs e)
{
    if(e.Key == Key.S || e.Key == Key.N)
    {
        e.Handled = false;
    }
    else
    {
        e.Handled = true;
    }
}
  • Ah, so pass the parameter e and if you use e.Key compared to a value?? I get it, very grateful Perozzo !! This will be very useful

  • 1

    In fact the e.Key is the key pressed inside the Textbox. Nothing needs to be passed by parameter. Creating the way I showed you, it’s all done automatically. And yes, just use the e.Key and test with the desired key.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.