Mathi901
Mathi901

Reputation: 245

Delete TextBox content when Backspace key is pressed C#

I'm trying to delete the content of a TextBox when the backspace key is pressed, but it is not working. The code:

private void txtConteudo_TextChanged(object sender, TextChangedEventArgs e)
    {
        if(Keyboard.IsKeyDown(Key.Back))
        {
            txtConteudo.Text = "";
        }
    }

The xaml of the textbox:

<TextBox x:Name="txtConteudo" Text="0" FontSize="16" IsReadOnly="True" Margin="10,5,16,139" TextChanged="txtConteudo_TextChanged" />

Upvotes: 0

Views: 2471

Answers (3)

Developer Nation
Developer Nation

Reputation: 384

First of all, you shouldn't use textchanged event for that. Instead use KeyDown event

private void txtConteudo_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyData == Key.Back)
    {
        txtConteudo.Text = "";
    }
}

Upvotes: 0

Chandrashekar Jupalli
Chandrashekar Jupalli

Reputation: 347

Try this

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 8)
            {
                textBox1.Text = "";
            }
        }

Upvotes: 0

Bijington
Bijington

Reputation: 3751

You want to use the PreviewKeyDown event instead. Try changing your current code to:

Code:

private void txtConteudo_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.Back))
    {
        txtConteudo.Text = "";
    }
}

Xaml:

<TextBox x:Name="txtConteudo" Text="0" FontSize="16" IsReadOnly="True" Margin="10,5,16,139" PreviewKeyDown="txtConteudo_PreviewKeyDown" />

Upvotes: 1

Related Questions