Home > Visual Basic > Visual Basic การใช้ตัวเลือกการตัดสินใจ If

Visual Basic การใช้ตัวเลือกการตัดสินใจ If

March 13, 2010 No Comments    

ในการเขียนโปรแกรมนั้นจำเป็นต้องมีการใช้ตัวเลือกการตัดสินใจพวก If else ต่างๆ เพื่อให้โปรแกรมมีประสิทธิภาพมากขึ้น ใน vb ก็มีเหมือนกันแต่ใน Visual basic นั้นจะเป็นรูปแบบ If ต่างจากภาษาพวก ภาษาซี จาวา คือจะต้องจบ If ด้วย End If ?นั้นเอง ต่อมาก็มาดูตัวอย่างใน Visual basic กันเลยดีกว่า

โดยขั้นแรกก็สร้างแรเจ็คใหม่ก่อนโดยเลือกเป็น Window Form Application

new project visual basic

ตั้งชื่อว่า Simple if ?จากทำการสร้างปุ่มโดยกำหนด Text เป็น If ส่วน Name เป็น btnIf

visual basic if

จากนั้น Double ? Click ที่ปุ่มแล้วทำการเพิ่มโค้ดลงไป


Private Sub btnIf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIf.Click

'Declare and set a Variable

Dim intNumber As Integer = 27

'Here 's where you make a decision,

'and tell the user what happened

If intNumber = 27 Then

MessageBox.Show("'intNumber' is, indeed, 27!", "Simple If")

End If

End Sub

เมื่อทำการเพิ่มโค้ดเสร็จแล้วก็ทำการรันโดยการกด F5 จากนั้นลองกดปุ่ม If ดูจะเห็นผลลัพธ์ดังรูป

result if visual basic

หลักการทำงานของโปรแกรมนี้ก็มีอยู่ว่าในตอนแรกนั้นเราได้ทำการประกาศตัวแปรที่ชื่อว่า intNumber ซึ่งมีค่าเท่ากับ 27 แล้วเมื่อถึงคำสั่ง If ก็จะทำการตรวจสอบว่า intNumber นั้นเท่ากับ 27 หรือไม่ถ้าเท่ากับ 27 ก็จะแสดงกล่องข้อความออกมาแต่ถ้าไม่เท่ากับ 27 ก็จะไม่ทำแล้วก็ข้ามไป จะเห็นว่า If นั้นจะเป็นชุดคำสั่งที่จะทำในกรณีที่ตรงตามเงื่อนไขด้วย End If

Download SouceCode

Tags: , , , , , ,

Comments : Visual Basic การใช้ตัวเลือกการตัดสินใจ If

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>