Satu Kondisi: IF... THEN ...
Jika satu kondisi terpenuhi maka code result akan dijalankan (dieksekusi). Jika tidak memenuhi kondisi maka tidak ada code yang dieksekusi.
Sintaks:
(1 baris result)
If [kondisi] Then [Result]
(2 atau lebih baris result)
If [kondisi] Then
[Result]
[Result]
...
End If
Contoh:
UI:
Code:
Public Class Form1
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If i < 10 Then
i = i + 1
Label1.Text = i
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
If i > 0 Then i = i - 1 : Label1.Text = i
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
i = 0
Label1.Text = i
Button1.Text = "Tambah (+)"
Button2.Text = "Kurang (-)"
End Sub
End Class
Runtime:
Dua Kondisi: IF... THEN... ELSE...
Jika satu kondisi terpenuhi maka code result akan dijalankan (dieksekusi) dan jika tidak memenuhi kondisi maka code lain yang dieksekusi.
Sintaks:
If [kondisi] Then
[Result]
...
Else
[Result]
...
End If
Contoh:
UI:
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Text = "Apply Format"
CheckBox1.Text = "Red Font"
CheckBox2.Text = "Lightened"
Label1.Text = "SAMPLE TEXT"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then
Label1.ForeColor = Color.Red
Else
Label1.ForeColor = Color.Black
End If
If CheckBox2.Checked = True Then
Label1.BackColor = Color.Yellow
Else
Label1.BackColor = Color.FromKnownColor(KnownColor.Control)
End If
End Sub
End Class
Runtime:
Tiga atau Lebih Kondisi: IF... THEN... ELSEIF...
Terdapat beberapa kondisi, jika menemukan kondisi pertama yang sesuai maka code result dibawah nya akan dijalankan. Jika belum sesuai maka akan memeriksa kondisi selanjutnya. Jika ingin menambahkan code result untuk kondisi yang tidak sesuai dengan pilihan kondisi yang tersedia code result dibawah Else dapat ditambahkan.
Sintaks:
If [kondisi] Then
[Result]
...
ElseIf [kondisi] Then
[Result]
...
Else
[Result]
...
End If
Contoh:
UI:
Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = 0
Button1.Text = "Show Result!"
Label1.Text = "[result]"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If CSng(TextBox1.Text) >= 80 Then
Label1.Text = "Nilai A"
ElseIf CSng(TextBox1.Text) >= 70 Then
Label1.Text = "Nilai B"
ElseIf CSng(TextBox1.Text) >= 60 Then
Label1.Text = "Nilai C"
ElseIf CSng(TextBox1.Text) >= 50 Then
Label1.Text = "Nilai D"
Else
Label1.Text = "Nilai E"
End If
End Sub
End Class
Runtime:
Click here if you like this article.
0 Comments