简体   繁体   中英

C# How to check textbox

I'm new on c# and I have got a question to ask you.

I want to make a small translator with some words.

private void button1_Click(object sender, EventArgs e)
{
    string i;
    i = textBox1.Text;
    if (textBox1.Text == bonjour) ;
    {
         label1.Text = "Hello";
    }

    if (textBox1.Text == Hello) ;
    {
        label1.Text = "bonjour";
    }
}

But label always "bonjour". Where did I go wrong?

This works with some changes.

     string i;
        i = textBox1.Text;
        if (textBox1.Text == "bonjour") //Remove the ";" and put quotes around string
        {
            label1.Text = "Hello";
        }

        if (textBox1.Text == "Hello") 
        {
            label1.Text = "bonjour";
        }

I would also suggest, if case does not matter, the following:

        string i;
        i = textBox1.Text;
        if (textBox1.Text.ToLower() == "bonjour") 
        {
            label1.Text = "Hello";
        }

        if (textBox1.Text.ToLower() == "hello") 
        {
            label1.Text = "bonjour";
        }
private void button1_Click(object sender, EventArgs e)
{
    string i;
    i = textBox1.Text;
    if (textBox1.Text == "bonjour")
    {
         label1.Text = "Hello";
    }

    if (textBox1.Text == "Hello")
    {
        label1.Text = "bonjour";
    }
}

You don't want semicolons at the end of tests. Also, you need double quotes "" around the strings you're testing for.

With the way you've set this up, you could also do this:

private void button1_Click(object sender, EventArgs e)
{
    string i;
    i = textBox1.Text;
    if (i == "bonjour")
    {
         label1.Text = "Hello";
    }

    if (i == "Hello")
    {
        label1.Text = "bonjour";
    }
}

Furthermore, you have no way of testing case, so use .ToLower(), as suggested by Matt Cullinan.

private void button1_Click(object sender, EventArgs e)
{
    string i;
    i = textBox1.Text;
    if(textBox1.Text == "bonjour");
    {
        label1.Text = "Hello";
    }

    else if(textBox1.Text == "Hello");
    {
        label1.Text = "bonjour";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM