Reputation: 21
I'm having trouble understanding this code:
SaveFileDialog.InitialDirectory = "C:\"
SaveFileDialog.FileName = "dummy.txt"
SaveFileDialog.Filter = "txt files (*.txt)|*.txt"
If (SaveFileDialog.ShowDialog() = 2) Then
MsgBox("No dummy has been created", MsgBoxStyle.OkOnly)
Else
Dim StreamWriter As StreamWriter = File.CreateText(SaveFileDialog.FileName)
I want to know what the "2" means at the beginning of the If statement in this code.
Note: I didn't write this code. This is an example my teacher gave to us.
Upvotes: 1
Views: 172
Reputation: 7804
When you call the SaveFileDialog.ShowDialog
Method a DialogResult
is returned. The DialogResult
is an enumeration and look like this
public enum DialogResult
{
None, // 0
OK, // 1
Cancel, // 2 !!
Abort, // 3
Retry,
Ignore,
Yes,
No, // 7
}
In this case, each enumeration value has an implicit numerical index beginning from zero. In your code sample the code evaluates the DialogResult
based on the index instead of the actual enumeration value.
This means that evaluating whether the DialogResult
is equal to 2 is equivalent to evaluating whether the DialogResult
is equal to DialogResult.Cancel
.
This means that when the user presses the cancel button on the dialog window, the MessageBox
should be displayed informing the user that they did not select a file.
Upvotes: 3
Reputation: 17402
2 is the dialog result (enumeration value) of the ShowDialog
call.
The DialogResult
maps to the following enumeration: http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult.aspx
So, by checking
If (SaveFileDialog.ShowDialog() = 2) Then
MsgBox("No dummy has been created", MsgBoxStyle.OkOnly)
the code is validating whether or not the user selected CANCEL on the dialog.
The code should also be written using the enumeration value for the check, which makes it more clear:
If (SaveFileDialog.ShowDialog() = DialogResult.Cancel) Then
MsgBox("No dummy has been created", MsgBoxStyle.OkOnly)
Upvotes: 1