Sainath
Sainath

Reputation: 999

unable to clear a textbox data

I'm not able to delete textbox data with the code below

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

tried using clear method as well the alphabet i entered stays in the textbox and when i type any key it get overwritten but i want the textbox to be empty the second time and the prev data to be removed

Upvotes: 1

Views: 2312

Answers (4)

sheikh
sheikh

Reputation: 3

Add this to your text box key press event your problem will be solved

e.handle = true;

Upvotes: 0

CodeCamper
CodeCamper

Reputation: 6980

You are doing it wrong. You can just paste in a bunch of letters with Ctrl+V. Delete the KeyDown event and create a TextChanged event. This code should accomplish what you are attempting. Please tell me if there is any more details and I will add to my answer.

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

Upvotes: 0

NDJ
NDJ

Reputation: 5194

you just need to say you've handled the event:

    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
        }
    }

Upvotes: 3

Freelancer
Freelancer

Reputation: 9074

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

This will clear your textbox.

Upvotes: 0

Related Questions