如何禁止用户在文本框中输入相同的输入?

时间:2014-08-21 15:17:15

标签: c# variables textbox

我知道我做错了,因为它仍然可以接受来自文本框的相同输入。有人可以帮我解决这个愚蠢的伎俩。

private void btnSpot_Click(object sender, EventArgs e)
{
    string animal=txtAnimal.Text;

    if (i <= 3)
    {
        string insertedAnimal = "";

        if (insertedAnimal!=txtAnimal.Text)
        {              
            if (animal == "Cheetah" || animal == "Giraffe")
            {
                lboDisp.Items.Add("Animal " + i + ": " + animal + ".");
                lboDisp.Items.Add(" A " + animal + " has spots.");
                lboDisp.Items.Add("");
                j++;
            }

            else
            {
                lboDisp.Items.Add("Animal " + i + ": " + animal + ".");
                lboDisp.Items.Add("I don't think that a " + animal + " has spots.");
                lboDisp.Items.Add("");
            }

            lblResult.Text = j + " of animals you have entered have spots.";
            i++;
        }

        else
        {
            MessageBox.Show("You've entered the same animal");
        }
        insertedAnimal = txtAnimal.Text;        
    }
    else
    {
        MessageBox.Show("Press Reset button to restart program");
    }     
}

2 个答案:

答案 0 :(得分:2)

我认为问题在于这一行:

 string insertedAnimal = "";

如果用户在txtAnimal中输入了动物,它将始终不同。您需要将insertedAnimal设置为等于用户之前的输入。

答案 1 :(得分:0)

你必须移动

string insertedAnimal = "";

在方法之外,作为局部变量:

class SomeClass // Whatever the name of your class is
{
    private string insertedAnimal = "";
    private void btnSpot_Click(object sender, EventArgs e)
    {
        // Your code
    }
}

这样,它只会在创建表单时设置为"",而不是每次按下按钮时,当您确实想要将旧值与之比较时。