Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a, b, sum As Integer
a = TextBox1.Text
b = TextBox2.Text
If RadioButton1.Checked = True Then
sum = a + b
ElseIf RadioButton2.Checked = True Then
sum = a - b
ElseIf RadioButton3.Checked = True Then
sum = a * b
ElseIf RadioButton4.Checked = True Then
sum = a / b
ElseIf RadioButton5.Checked = True Then
sum = a \ b
ElseIf RadioButton6.Checked = True Then
sum = a Mod b
ElseIf RadioButton7.Checked = True Then
sum = a ^ b
End If
textbox3.Text = sum
End Sub
End class
ซึ่งมันก็ทำงานปกติดี ตัวเครื่องหมายทำงานถูกทุกตัว
จากนั้นผมอยากลองใช้ select case แทน if ออกมาเป็น code แบบนี้
Code (VB.NET)
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a, b, sum As Integer
a = TextBox1.Text
b = TextBox2.Text
Select Case sum
Case RadioButton1.Checked = True
sum = a + b
Case RadioButton2.Checked = True
sum = a - b
Case RadioButton3.Checked = True
sum = a * b
Case RadioButton4.Checked = True
sum = a / b
Case RadioButton5.Checked = True
sum = a \ b
Case RadioButton6.Checked = True
sum = a Mod b
Case Else
sum = a ^ b
End Select
textbox3.Text = sum
End Sub
End class
'Sum as Integer ถ้าไม่กำหนดค่า Default จะมีค่า = 0
Select Case sum
'เช่นเดียวกันถ้า Select Case 0 จะไม่ตรงกับเงื่อนไขใดเลย ก็จะไปทำงานที่
Case Else
sum = a ^ b
Private Sub Button1_Click _
(ByVal s As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Dim a As Double = Val(TextBox1.Text)
Dim b As Double = Val(TextBox2.Text)
Dim sum As Double = 0.0
Select Case True
Case RadioButton1.Checked
sum = a + b
Case RadioButton2.Checked
sum = a - b
Case RadioButton3.Checked
sum = a * b
Case RadioButton4.Checked
sum = a / b
Case RadioButton5.Checked
sum = a \ b
Case RadioButton6.Checked
sum = a Mod b
Case Else
sum = a ^ b
End Select
TextBox3.Text = sum.ToString()
End Sub