ASP.NET if else statements


The If Condition

C# lets you execute code based on conditions.

To test a condition you use an if statement. The if statement returns true or false, based on your test:

  • The if statement starts a code block
  • The condition is written inside parenthesis
  • The code inside the braces is executed if the test is true

Synatx

 
if (condition)
	statement;

Example of if Statement (C# Code)

 
using System;

public partial class _Default : System.Web.UI.Page 
{
	protected void Button1_Click(object sender, EventArgs e)
	{
		int num1, num2;

		num1 = 50;

		if (num1 > 30)
		{
			Label1.Text = "The Number is too high";
		}
	}
}

HTML Code

<html>
<body>
	<form id="form1" runat="server">
	<div>
		<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
		<br />
		<asp:Label ID="Label1" runat="server" Text="Label">
	</div>
	</form>
</body>
</html>

Output

The Number is too high

The Else Condition

An if statement can include an else condition.

The else condition defines the code to be executed if the condition is false.

Synatx

 
if (condition)
	statement;
  else
	statement;

Example of if else Statement (C# Code)

 
using System;

public partial class _Default : System.Web.UI.Page 
{
	protected void Button1_Click(object sender, EventArgs e)
	{
		int num1, num2;

		num1 = 100;
		num2 = 200;

		if (num1 > num2)
		{
			Label1.Text = "Num1 is greater than num2";
		}
		else
		{
			Label1.Text = "Num2 is greater than num1";
		}
	}
}s

HTML Code

<html>
<body>
	<form id="form1" runat="server">
	<div>
		<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
		<br />
		<asp:Label ID="Label1" runat="server" Text="Label">
	</div>
	</form>
</body>
</html>

Output

Num2 is greater than num1

The Else If Condition

Multiple conditions can be tested with an else if condition:

Synatx

 
  if (condition)
	statement;
  else if (condition)
	statement;
  else
	statement;

Example of if else if Statement (C# Code)

 
using System;

public partial class _Default : System.Web.UI.Page 
{
	protected void Button1_Click(object sender, EventArgs e)
	{
		int grade;

		grade = 60;

		if (grade == 100)
		{
			Label1.Text = "A+ Grade";
		}
		else (grade == 60)
		{
			Label1.Text = "C Grade";
		}
        else
        {
            Label1.Text = "Fail";
		}
	}
}

In the example above, if the first condition is true, it will be executed.

If not, then if the next condition is true, this condition will be executed.

You can have any number of else if conditions.

If none of the if and else if conditions are true, the last else block (without a condition) covers "everything else".

HTML Code

<html>
<body>
	<form id="form1" runat="server">
	<div>
		<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
		<br />
		<asp:Label ID="Label1" runat="server" Text="Label">
	</div>
	</form>
</body>
</html>

Output

C Grade

Share this article on