无法清除文本框数据

本文关键字:数据 文本 清除 | 更新日期: 2023-09-27 18:16:47

我不能用下面的代码删除文本框数据

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {            
        if(char.IsDigit(e.KeyChar)==false)
        {
            count++;
       }
        if (count == 1)
        {
            textBox1.Text = ("");
            count = 0;
        }
   }

尝试使用clear方法以及我输入的字母留在文本框中,当我键入任何键时,它会被覆盖,但我希望文本框第二次为空,前一个数据被删除

无法清除文本框数据

你只需要说你已经处理了这个事件:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (char.IsDigit(e.KeyChar) == false)
        {
            count++;
        }
        if (count == 1)
        {
            textBox1.Text = ("");
            count = 0;
            e.Handled = true; // this bit fixes it
        }
    }

use textBox1.Text = ""; OR textBox1.clear();

清空文本框

你做错了。你可以用Ctrl+V粘贴一堆字母。删除KeyDown事件并创建TextChanged事件。这段代码应该可以完成您所尝试的工作。如果有更多的细节请告诉我,我会补充我的答案。

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        foreach (char c in textBox1.Text)
        if (!char.IsDigit(c)) { textBox1.Clear(); break; }
    }

将此添加到文本框按键事件中,问题就解决了

e.handle = true;