开发者

C# How can I clear a textbox when the backspace button is pressed

I'm using C# and working on a Winform program, when a users clicks in a textbox and presses the backspace button I want to clear the textbox rather than del开发者_StackOverflow社区ete one character at a time. How can I do this?

Many thanks Steve


You could subscribe to the KeyPress event and clear the text of the sender:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 8)
    {
        ((TextBox)sender).Clear();
    }
}


If this is a field users will be entering text into, please consider that some users (like me) have the natural inclination to hit Backspace when they make a typo. I would find it annoying if doing that cleared everything I had just typed in.

As an alternative, you could add this behavior if they did a Shift-Backspace. The code below will delete everything before the caret on a Shift-Backspace, but will also leave the expected behavior of deleting only the selection if the user has selected text:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    // if shift-backspace is pressed and nothing is selected, 
    // delete everything before the caret
    if (e.Shift && e.KeyCode == Keys.Back && textBox1.SelectionLength == 0)
    {
        textBox1.Text = textBox1.Text.Substring(textBox1.SelectionStart);
        e.Handled = true;
    }
}


private void button1_Click(object sender, EventArgs e)
{
    int textlength = textBox1.Text.Length;
    if (textlength > 0)
    {
        textBox1.Text = textBox1.Text.Substring(0, textlength - 1);
    }
    textBox1.Focus();
    textBox1.SelectionStart = textBox1.Text.Length;
    textBox1.SelectionLength = 0;
}


Subscribe to the KeyDown event and when the pressed key equals backspace, you just have to clear the textbox.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜