if..then..else

protected void Button1_Click(object sender, EventArgs e)

{

        if (DetailsView1.Visible == false) then;

        Button1.Text = "Update";

        DetailsView1.Visible = true ;

        else ;

        Button1.Text = "New" ;

        DetailsView1.Visible = false ;

        End if;

}

Hi there! I am a hobby code writer. I am new to C# here. The above is the code I try to generate but having problem. When I try to debug it say that "Invalid expression term 'else'". I am also unable to try "End if" in the intellisense. Can anyone tell me what is wrong.............................................please



Answer this question

if..then..else

  • Misha Shneerson - MSFT

    stick with it. . . pretty soon it will be flowing off your finger tips and you will never look back!!!

    cheers!



  • GDocherty

    the "{" and "}" represent code blocks.

    "if" doesn't take a "then" in c#

    ";" is the end of a statement therefore you dont need a ";" at the end of the "if" line becaues the statement is not complete, it needs the code block. same thing with the "else" that is unless you want the "if" and/or "else" to have an empty block.

    protected void Button1_Click(object sender, EventArgs e)
    {
            if (DetailsView1.Visible == false)
            {
                    Button1.Text = "Update";
                    DetailsView1.Visible = true;
            }
            else 
            {
                    Button1.Text = "New";
                    DetailsView1.Visible = false;
            }
    }

    Also, you only need the "{" and "}" in the if/else code blocks if the code blocks are multi statement. If single statement you can follow jsut with the statement.

    protected void Button1_Click(object sender, EventArgs e)
    {
            if (DetailsView1.Visible == false)
                   DoSomething(); 
             else 
                   DoSomethingElse(); 
     }

    you can even keep them on the same line, but this is a matter of style (some don't like it)

            if (DetailsView1.Visible == false) DoSomething(); 
           else DoSomethingElse(); 

     

     



  • maria paramita

    Exactly. That where it get me nowhere in C#. Thanks for clearing me up.
  • fradi

    Oh I see.

    I now know where I've been (completely) wrong.

    Thank you so much.


  • Ravish Subramanya

    Hi Yok,

    It looks like you're trying to mix syntax learned in VB into something intended for C#.

    Grouping multi-line statements or functions typically require curly-brackets in C# - there is no "end" keyword in C#. So try the following:

    if(DetailsView1.Visible == false){

    }else{

    }

    "C" style syntax is much different than "basic", thus the feuds that often take place surrounding the different languages :-)

    Good luck, and happy coding.



  • if..then..else