I am having a problem with my code.

I was trying to make an application. the application is very simple but when i was typing the code it said there was two errors. The first error was ('ElseIf' must be preceded by a matching 'If' or 'ElseIf'.) The second error was ('End If' must be preceded by a matching 'If'.) I really need help to get this code error free. The code is at the end of this page. Thanks for helping.

The code

Public Class Form1
Dim door As String = "locked"

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If door = "locked" Then Button1.Text = "Unlock"
Label1.Text = "The door is locked"
MessageBox.Show("The door is locked.")
door = "unlocked"

ElseIf door = "unlocked" Then Button1.Text = "Lock"
MessageBox.Show("The door is unlocked.")
Label1.Text = "The door is unlocked"
door = "locked"
End if


End Sub
End Class

[1078 byte] By [jcnconnect] at [2007-12-25]
# 1

The problelm apears to be after the "THEN" keyword. I believe this should be the last word on the line of an If statement.

If you change you code as follows it should work...


If door = "locked" Then

Button1.Text = "Unlock"
Label1.Text = "The door is locked"
MessageBox.Show("The door is locked.")
door = "unlocked"
ElseIf door = "unlocked" Then

Button1.Text = "Lock"
MessageBox.Show("The door is unlocked.")
Label1.Text = "The door is unlocked"
door = "locked"
End If


tattoo at 2007-9-3 > top of Msdn Tech,Visual Studio Express Editions,Visual Basic 2005 Express Edition...
# 2

As a side note, if you only want a single statement to be executed on an 'if' condition, you can put it on one line and not require an 'end if'. For example:

If door = "locked" then Button1.text = "Unlock"

is equivalent to:

If door = "locked" then
Button1.text = "Unlock"
end if

If you need multiple statements (as you evidently do, here), then it needs to be written as a block with a matching 'end if'.

SJWhiteley at 2007-9-3 > top of Msdn Tech,Visual Studio Express Editions,Visual Basic 2005 Express Edition...
# 3
Thanks.
jcnconnect at 2007-9-3 > top of Msdn Tech,Visual Studio Express Editions,Visual Basic 2005 Express Edition...