RisenShadow
RisenShadow

Reputation: 57

C# How to check textbox

I'm new in c#, 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?

Upvotes: 1

Views: 76

Answers (3)

Evilfaic
Evilfaic

Reputation: 55

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.

Upvotes: 1

Matt Cullinan
Matt Cullinan

Reputation: 108

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

Upvotes: 2

M.S.
M.S.

Reputation: 4433

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

Upvotes: 0

Related Questions