Jacob Sedore
Jacob Sedore

Reputation: 37

Clearing out a c# form text box

I am making a simple hangman style game in a C# form. I have it set as textBox1_TextChanged. Except everytime the user backspaces their guess letter it takes in blank space. How can I make it so after the message saying right/wrong it clears the space. I am getting annoyed at it telling the user they made a wrong guess after they backspace. This is my first post on this forum so sorry if the code text is weird. I just want the program to clear the text in the textBox after they guess.

UPDATE: Added suggested information. Now it does everything it is supposed to do. Except it pops up a windows saying " was found in the target word". This happens if guessLetter == null || guessLetter == correct || guessLetter == false.

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string guessLetter = textBox1.Text;
        //textBox1.ReadOnly = true;


        if (targetWord == null)
        {
            MessageBox.Show("Please start a new game.");
            textBox1.Text = ("");

        }

        else
        {
            if (targetWord.Contains(guessLetter))
            {


                MessageBox.Show(guessLetter + " was found in the word");
            }

            else
            {
                MessageBox.Show(guessLetter + " was not found in the word");
                incorrectGuessCtr++;
                textBox3.Text = incorrectGuessCtr.ToString();
            }
            textBox1.Text = ("");
        }
    }

Upvotes: 0

Views: 93

Answers (2)

minimanimo
minimanimo

Reputation: 195

You will enter this event when you write code that changes Text property in textbox. I mean this.

  textBox3.Text = incorrectGuessCtr.ToString();

Put something in function arguments or set some flags so that you can identify whether the event is called from user input or your clearing the text. Just check how many times this function is called when user press backspace. You will get the idea.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156898

Don't only check if the targetWord is null, but also the guessLetter. You'd better use string.IsNullOrEmpty too, since it also checks if the string is empty:

if (!string.IsNullOrEmpty(targetWord) && !string.IsNullOrEmpty(guessLetter))
{
    ...
}

I guess you should also check if there is exactly one letter entered. That would mean this additional check:

if (guessLetter.Length == 1)
{
    ...
}

Upvotes: 1

Related Questions