简体   繁体   中英

Visual Studio C# if / else syntax error

I have a problem with my if/else code :/

private void btn_Convert_Click(object sender, EventArgs e)
{
    if (rbtn_Bitcoin = checked)
    {
        webBrowser1.Navigate("http://preev.com/btc/sek");
    }

    else
    {
        webBrowser1.Navigate("http://preev.com/ltc/sek");
    }
}

if (rbtn_Bitcoin = checked) after this statement I get three errors, "Syntax error, '(' expected" and two ") expected"

Your code has two errors:

  • checked is a reserved keyword. Therefore you cannot use it as a name of a variable
  • The other problem is that you use = which is the assignment operator and not the == which is the operator for equality comparison

= is assignment operator. == is equality operator.

I assume you want to get your radio button is checked or not, you can use RadioButton.Checked Property instead.

Gets or sets a value indicating whether the control is checked.

if (rbtn_Bitcoin.Checked)
{
    webBrowser1.Navigate("http://preev.com/btc/sek");
}
else
{
    webBrowser1.Navigate("http://preev.com/ltc/sek");
}

Double the = and use checked property:

private void btn_Convert_Click(object sender, EventArgs e)
{
    if (rbtn_Bitcoin.Checked == true) <<-- == instead of =
    {
        webBrowser1.Navigate("http://preev.com/btc/sek");
    }

    else
    {
        webBrowser1.Navigate("http://preev.com/ltc/sek");
    }
}

Also checked is a reserved word, you can't use that this way. if you want to check whether the radio button is checked, use the Checked property.

You can also omit the == true part:

if (rbtn_Bitcoin.Checked) 
{
}

Assuming rbtn_Bitcoin is a radio button:

private void btn_Convert_Click(object sender, EventArgs e)
{
    if (rbtn_Bitcoin.Checked)
    {
        webBrowser1.Navigate("http://preev.com/btc/sek");
    }

    else
    {
        webBrowser1.Navigate("http://preev.com/ltc/sek");
    }
}

The question is already answered.

But if rbtn_Bitcoin is a radio button then you can use the following code directly without any comparison using == sign

private void btn_Convert_Click(object sender, EventArgs e)
{
    if (rbtn_Bitcoin.IsChecked)
    {
        webBrowser1.Navigate("http://preev.com/btc/sek");
    }

    else
    {
        webBrowser1.Navigate("http://preev.com/ltc/sek");
    }
}

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